注意:reduce需要 from functools import reduce
map的使用:
>>> def func(x): ... return x*x ... >>> [x for x in range(1,11)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> l=[x for x in range(1,11)] >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> print(map(func,l)) <map object at 0x014E94F0> >>> ll=list(map(func,l)) #重点用法 >>> ll [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
reduce用法:
>>> l=[i for i in range(1,6)] >>> l [1, 2, 3, 4, 5] >>> def func(x,y): ... return(x*10+y) ... >>> reduce(func,l) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘reduce‘ is not defined #单个数乘10,组成一个整数 >>> from functools import reduce #重点 >>> reduce(func,l) #重点 12345 >>> ll=reduce(func,l) >>> type(ll) <class ‘int‘>
dd
时间: 2024-12-19 10:32:03