Python相当于zip的字典 [英] Python equivalent of zip for dictionaries
问题描述
如果我有这两个列表:
la = [1,2,3]
lb = [ 4,5,6]
我可以重复如下:
$ b $ (min(len(la),len(lb))):print la [i],lb [i] b
或更多的pythonically
a,b在zip(la,lb)中的$ code:
打印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()):
打印键,da [key],db [key]
是否有一些内建方法可以让我按照以下方式进行迭代?
for key,value_a,value_b in common_entries( da,db):
print key,value_a,value_b
没有内置的功能或方法可以做到这一点。但是,您可以轻松定义自己的。
def common_entries(* dcts):
for i in set(dcts [0])。交点(* 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()
。
>>>列表(common_entries(da))
[('c',3),('b',2),('a',1)]
If I have these two lists:
la = [1, 2, 3]
lb = [4, 5, 6]
I can iterate over them as follows:
for i in range(min(len(la), len(lb))):
print la[i], lb[i]
Or more pythonically
for a, b in zip(la, lb):
print a, b
What if I have two dictionaries?
da = {'a': 1, 'b': 2, 'c': 3}
db = {'a': 4, 'b': 5, 'c': 6}
Again, I can iterate manually:
for key in set(da.keys()) & set(db.keys()):
print key, da[key], db[key]
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
There is no built-in function or method that can do this. However, you could easily define your own.
def common_entries(*dcts):
for i in set(dcts[0]).intersection(*dcts[1:]):
yield (i,) + tuple(d[i] for d in dcts)
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)]
When only one dictionary is provided as an argument, it essentially returns dct.items()
.
>>> list(common_entries(da))
[('c', 3), ('b', 2), ('a', 1)]
这篇关于Python相当于zip的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!