如果我有这两个清单:
la = [1, 2, 3]
lb = [4, 5, 6]
我可以按如下方式迭代它们:
for i in range(min(len(la), len(lb))):
print la[i], lb[i]
或者更诡异
for a, b in zip(la, lb):
print a, b
如果我有两本词典怎么办?
da = {'a': 1, 'b': 2, 'c': 3}
db = {'a': 4, 'b': 5, 'c': 6}
同样,我可以手动迭代:
for key in set(da.keys()) & set(db.keys()):
print key, da[key], db[key]
是否有一些内置方法允许我迭代如下?
for key, value_a, value_b in common_entries(da, db):
print key, value_a, value_b
答案 0 :(得分:29)
没有可以执行此操作的内置函数或方法。但是,您可以轻松定义自己的。
def common_entries(*dcts):
for i in set(dcts[0]).intersection(*dcts[1:]):
yield (i,) + tuple(d[i] for d in dcts)
这建立在"手动方法"你提供,但是,像zip
一样,可以用于任何数量的词典。
>>> da = {'a': 1, 'b': 2, 'c': 3}
>>> db = {'a': 4, 'b': 5, 'c': 6}
>>> list(common_entries(da, db))
[('c', 3, 6), ('b', 2, 5), ('a', 1, 4)]
当只提供一个字典作为参数时,它基本上返回dct.items()
。
>>> list(common_entries(da))
[('c', 3), ('b', 2), ('a', 1)]
答案 1 :(得分:9)
您可能希望使用Python Set类型创建交集。
da = {'a': 1, 'b': 2, 'c': 3, 'e': 7}
db = {'a': 4, 'b': 5, 'c': 6, 'd': 9}
dc = set(da) & set(db)
for i in dc:
print i,da[i],db[i]
干杯,
ķ。
答案 2 :(得分:3)
Dictionary key views。您可以删除set()
:
for key in da.keys() & db.keys():
print(key, da[key], db[key])
在Python 2中:
for key in da.viewkeys() & db.viewkeys():
print key, da[key], db[key]
答案 3 :(得分:1)
如果有人正在寻找通用解决方案:
import operator
from functools import reduce
def zip_mappings(*mappings):
keys_sets = map(set, mappings)
common_keys = reduce(set.intersection, keys_sets)
for key in common_keys:
yield (key,) + tuple(map(operator.itemgetter(key), mappings))
或者如果您想将键与值分开并使用
之类的语法for key, (values, ...) in zip_mappings(...):
...
我们可以用
替换最后一行yield key, tuple(map(operator.itemgetter(key), mappings))
from collections import Counter
counter = Counter('abra')
other_counter = Counter('kadabra')
last_counter = Counter('abbreviation')
for (character,
frequency, other_frequency, last_frequency) in zip_mappings(counter,
other_counter,
last_counter):
print('character "{}" has next frequencies: {}, {}, {}'
.format(character,
frequency,
other_frequency,
last_frequency))
给我们
character "a" has next frequencies: 2, 3, 2
character "r" has next frequencies: 1, 1, 1
character "b" has next frequencies: 1, 1, 2
(在Python 2.7.12
& Python 3.5.2
上测试)
答案 4 :(得分:0)
Python3:以下内容如何?
da = {'A': 1, 'b': 2, 'c': 3}
db = {'B': 4, 'b': 5, 'c': 6}
for key, (value_a, value_b) in {k:(da[k],db[k]) for k in set(da)&set(db)}.items():
print(key, value_a, value_b)
上面的代码段打印了通用键(“ b”和“ c”)的值,并丢弃了不匹配的键(“ A”和“ B”)。
为了将所有键包含在输出中,我们可以使用稍作修改的理解:{k:(da.get(k),db.get(k)) for k in set(da)|set(db)}
。