filter, zip, map, reduce, all, any
# all 判断是否有布尔值有False的值 # any 判断是否有布尔值有True的值 lst = [1, 2, 3, '', 4, []] print(all(lst)) # False print(any(lst)) # True #zip: 拉链方法 lst1 = [1,2,3,4] lst2 = [5,6,7,8] z = zip(lst1, lst2) # 迭代器 print(list(z)) # [(1, 5), (2, 6), (3, 7), (4, 8)] # filter(function or None, iterable): 过滤 def larger(x): return x>5 lst = [3,4,5,6,7] ret = filter(larger, lst) print(list(ret)) # [6, 7] # map(func,*iterables): 依次处理iterables里的每一个元素,并返回一个可迭代对象 def self_add_one(x): return x+1 lst = [3,4,5,6,7] ret = map(self_add_one,lst) print(list(ret)) # [4, 5, 6, 7, 8] # reduce, py3 reduce被移到了functools模块 # reduce(function, sequence[, intiial]): 将sequence里的所有元素通过function方法压缩成一个值,必返回 from functools import reduce lst = [3,4,5,6,7] def my_add(x,y): return x+y ret = reduce(my_add, lst) print(ret) # 25 # sorted(iterable, key, reverse) # iterable: 可迭代对象 # key: 按照提供的key排序 # reverse: 是否反转序列 lst1 = [8, 5, -6, 7] lst2 = lst1[:] lst1.sort() print(lst1) # [-6, 5, 7, 8] ret = sorted(lst2, key=abs) print(ret) # [5, -6, 7, 8]