Python内建map、reduce、filter和sorted函数
from functools import reduce
# 计算平方
def power(x):
return (x) * (x)
# 获取数字值
def digit(x):
d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return d[x]
# 字符串转化为数字
def str2int(x, y):
return x * 10 + y
# map函数计算列表每个元素的平方
print(list(map(power, [1, 2, 3])))
# reduce计算字符串对应的数字值
print(reduce(str2int, list(map(digit, '13579'))))
def is_odd(x):
return x % 2
# 过滤掉偶数部分
print(list(filter(is_odd, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
def is_empty(s):
return s and s.strip()
# 过滤掉空字符串
print(list(filter(is_empty, [' 1', '', '23', ' '])))
print(sorted([-10, 12, 1, -14]))
print(sorted([-10, 12, 1, -14], key=abs))
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))