問題描述
如果我有這兩個(gè)列表:
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
<小時(shí)>
如果我有兩本字典怎么辦?
What if I have two dictionaries?
da = {'a': 1, 'b': 2, 'c': 3}
db = {'a': 4, 'b': 5, 'c': 6}
同樣,我可以手動(dòng)迭代:
Again, I can iterate manually:
for key in set(da.keys()) & set(db.keys()):
print key, da[key], db[key]
是否有一些內(nèi)置方法可以讓我進(jìn)行如下迭代?
Is there some builtin method that allows me to iterate as follows?
for key, value_a, value_b in common_entries(da, db):
print key, value_a, value_b
推薦答案
沒有內(nèi)置函數(shù)或方法可以做到這一點(diǎn).但是,您可以輕松定義自己的.
There is no built-in function or method that can do this. However, you could easily define your own.
def common_entries(*dcts):
if not dcts:
return
for i in set(dcts[0]).intersection(*dcts[1:]):
yield (i,) + tuple(d[i] for d in dcts)
這建立在手動(dòng)方法"的基礎(chǔ)上.您提供,但像 zip
一樣,可用于任意數(shù)量的字典.
This builds on the "manual method" you provide, but, like zip
, can be used for any number of dictionaries.
>>> 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)]
當(dāng)只提供一個(gè)字典作為參數(shù)時(shí),它本質(zhì)上返回 dct.items()
.
When only one dictionary is provided as an argument, it essentially returns dct.items()
.
>>> list(common_entries(da))
[('c', 3), ('b', 2), ('a', 1)]
沒有字典,它返回一個(gè)空的生成器(就像 zip()
)
With no dictionaries, it returns an empty generator (just like zip()
)
>>> list(common_entries())
[]
這篇關(guān)于Python 相當(dāng)于 zip 的字典的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!