chunk
Chunks an list into smaller lists of a specified size.
Uses range to create a list of desired size. Then use map on this list and fill it with splices of lst.
from math import ceil
def chunk(lst, size):
return list(
# 使用map对列表里的每一个元素进行遍历并传值给lamda函数, 返回运算的结果
map(lambda x: lst[x * size:x * size + size], # 每次取出size长度list, 如lst[0:size], 超出则不取
list(range(0, ceil(len(lst) / size))))) # 向上取整
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
[[1, 2], [3, 4], [5]]
help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
from functools import reduce
help(reduce)
Help on built-in function reduce in module _functools:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
序列处理函数
- filter()
fiter过滤的,依次列表取值,符合就返回出来
- map
如果你要对列表每一个元素进行遍历,进行操作的话,用map,map也是依次取值,得到值进行定义的运算,返回每一个值运算的结果。
- reduce
reduce为逐次操作list里的每项,接收的参数为2个,最后返回的为一个结果
help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
list(filter(lambda x:x>0, [-1,-2,0,3,-3,4]))
[3, 4]