d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d2 = {'a': 1, 'b': 2, 'c': 3, 'e': 5}
d3 = {'a': 1, 'b': 2, 'c': 3, 'f': 6}
法1. 遍历
res = []
for k in d1:
if k in d2 and k in d3:
res.append(k)
print(res)
法2. 集合交集
>>> d2.keys?
# Docstring: D.keys() -> a set-like object providing a view on D's keys
# Type: builtin_function_or_method
>>> d1.keys() & d2.keys() & d3.keys()
{'a', 'b', 'c'}
法3. map + reduce 函数
# map用法: map(func, list), 也就是对list中的每一个值做func操作
l1 = range(5)
print(list(map(lambda x: x**2, l1)))
# reduce用法: reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,
# reduce把结果继续和序列的下一个元素做累积计算,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
from functools import reduce
print(reduce(lambda x, y: x*10 +y, [1, 2, 3, 4]))
# map 函数和 reduce , 不会用的看后边
map(dict.keys, [d1, d2, d3])
print(reduce(lambda a, b: a&b, map(dict.keys, [d1, d2, d3])))
# reduce小练习: str to int
str1 = '23456'
def str2int(s):
def char2num(c):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[c]
from functools import reduce
return reduce(lambda x, y: x*10 + y, map(char2num, s))
print(str2int(str1))