我有很多字典:
dicts = [{'a': 1, 'b': 2, 'c': 1, 'd': 8}, {'c': 4, 'b': 3}, {'a': 9, 'b': 14}, ...]
我想找出它们的共同点。
因此,f(dicts) == {'b'}
在这种情况下。
我假设
set.intersection(*map(dict.keys, dicts))
可以,但出现错误
TypeError: descriptor 'intersection' for 'set' objects doesn't apply to a 'dict_keys' object
因此,它看起来像dict.keys
返回一个拒绝处理的dict_keys
对象set.intersection
。
是否有同样简洁的方法来获取某些对象的集合交集dict_keys
?还是我被迫reduce
与&
?
import functools
set(functools.reduce(lambda a, b: a & b, map(dict.keys, dicts)))
您可以将字典直接转换为set
s,而不是将dict_keys
对象转换为,然后可以将其传递给set.intersetcion()
:
dicts = [{'a': 1, 'b': 2, 'c': 1, 'd': 8}, {'c': 4, 'b': 3}, {'a': 9, 'b': 14}]
set.intersection(*map(set, dicts))
# {'b'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句