参考https://www.liaoxuefeng.com/wiki/1016959663602400/1017328525009056
一、map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回,范例:
[code language=”python”]
list_a=[1,3,5,1,2,3]
map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
map(str, [item for item in list_a]) #循环将每个元素转换为字符串
[str(item) for item in list_a] # 也可以简化成左边格式
[/code]
二、reduce把结果继续和序列的下一个元素做累积计算,类似reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4),范例:
[code language=”python”]
from functools import reduce
def fn(x, y):
return x * 10 + y
def char2num(s):
digits = {‘0’: 0, ‘1’: 1, ‘2’: 2, ‘3’: 3, ‘4’: 4, ‘5’: 5, ‘6’: 6, ‘7’: 7, ‘8’: 8, ‘9’: 9}
return digits[s]
reduce(fn, map(char2num, ‘13579’))
DIGITS = {‘0’: 0, ‘1’: 1, ‘2’: 2, ‘3’: 3, ‘4’: 4, ‘5’: 5, ‘6’: 6, ‘7’: 7, ‘8’: 8, ‘9’: 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
def prod(L):
def fn(x, y):
return x * y
return reduce(fn, L)
def str2float(s):
def fn(x, y):
return x+y/1000
return reduce( fn, map(float, s.split(‘.’)) )
if prod([3, 5, 7, 9]) == 945:
print(‘测试成功!’)
str2float("123.456")
[/code]
三、filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素,范例:
[code language=”python”]
def not_empty(s):
return s and s.strip()
list(filter(not_empty, [‘A’, ”, ‘B’, None, ‘C’, ‘ ‘]))
def is_palindrome(n):
s = str(n)
for i in range(0, int(round(float(len(s))/2))):
if s[i] != s[len(s)-i -1]:
return False
return True
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
print(‘测试成功!’)
v2_detail_array=[{"ps":"CN"}, {"ps":"CN2"}, {"ps":"US"}, ]
[ elm for elm in v2_detail_array if elm[‘ps’].find(‘CN’)>=0 ]
[/code]
四、关键字lambda表示匿名函数,冒号前面的x表示函数参数,lambda x: x * x,实际上就是
[code language=”python”]
def f(x):
return x * x
[/code]
范例:
[code language=”python”]
ip2int = lambda ip_str: reduce(lambda a, b: (a << 8) + b, [int(i) for i in ip_str.split(‘.’)])
ip2int("202.96.134.133")
[/code]
五、sorted() 函数对所有可迭代的对象进行排序操作, sorted(iterable, cmp=None, key=None, reverse=False),范例
[code language=”python”]
L = [(‘Bob’, 75), (‘Adam’, 92), (‘Bart’, 66), (‘Lisa’, 88)]
def by_name(t):
return t[0]
def by_score(t):
return t[1]
L2 = sorted(L, key=by_score)
L2 = sorted(L, key=by_name)
rank_list=[{"sort_value":11, "name":"b"}, {"sort_value":2, "name":"a"}]
sorted(rank_list, key=lambda i: i[‘sort_value’])
[/code]
六、其他例子:
[code language=”python”]
sum([item for item in list_a])
dict_a={ "key1": 1, "key2": 2 }
sum([obj for obj in dict_a.values()])
[/code]