序列处理函数的应用

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值