iterable obj dealing method
lambda
- eg. lambda <可省略参数>:[表达式]
- 冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值
- python3 的返回值:
- 对可迭代类型的处理:
- list eg.
lst=[1,2,4,5,6] s= lambda x:x*2,lst s:tuple (<function <lambda> at 0x00000159032017E0>, [1, 2, 4, 5, 6])
- list eg.
map()
use map fuction to deal with iter data struct:
map() return iter type
-
eg. t=map(square,[1,2,4,5,6]) print(t,type(t)) s=lambda x:x*2 for i in map(s,lst): print(i)
reduce()
reduce(function, iterable[, initializer])
from functools import reduce def f(x,y): return x*10+y print(reduce(lambda x,y:x*10+y,[1,2,3,4]))
reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) equals to sum([1,2,3,4,5])
Sort() and Sorted()
sorted(iterable[, key[, reverse]]])
key/reverse gives the rules of sorting
L=[('b',2),('a',1),('c',3),('d',4)] t=sorted(L,key=lambda x:x[1]) print(t) print(sorted(L,key=operator.itemgetter(1)))
sort 是 list 的一个方法,而 sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作
Filter()
filter(function, iterable)
filter out iterable data with function condition, return iterator
m=filter(lambda x:x[1]>3,L) print(list(m)) #creat a new list to print or for i in m: print(i)
Operator
-
operator.itemgetter(<num>)
- operator.itemgetter函数定义的是一个函数,通过该函数作用到对象上才能获取值
-
eg: import operator person = {"li":18,"zhang":50,"chang":60,"sun":22} lst=[i for i in range(10)] key=operator.itemgetter(1) print(key(lst)) print(person.items())# return tuple list:// dict_items([('li', 18), ('zhang', 50), ('chang', 60), ('sun', 22)]) for i in person.items(): print(i) print (max(person.items())) print (max(person.items(),key=operator.itemgetter(1)))