如何在一个循环中翻译两个字典? [英] How to travese two dictionaries in a single for loop?
问题描述
我想产生以下效果:
对于i,j在d.items()和k,v in c.items():
print i,j,k,v
这是错误的。我想知道如何实现这一点?
for(i,j) ,(k,v)in zip(d.items(),c.items()):
print i,j,k,v
记住,订单将是任意的,除非您的字典为 OrderedDict
s。要记忆效率
在Python 2.x(其中 dict.items
和 zip
创建列表)您可以执行以下操作:
from itertools import izip
/ pre>
for i,j),(k,v)in izip(d.iteritems(),c.iteritems()):
print i,j,k,v
这不一定会更快,因为您将在小列表中观察到,迭代这些中间列表的速度更快,但是您会注意到在重复迭代时的速度提升大数据结构
在Python 3.x中
zip
与izip
(不再存在)和dict.items
(dict.iteritems
不再存在)返回 视图 ,而不是列表。I want to generate the following effect :
for i, j in d.items() and k, v in c.items(): print i, j, k, v
This is wrong. I want to know how can I achieve this?
解决方案for (i, j), (k, v) in zip(d.items(), c.items()): print i, j, k, v
Remember the order will be arbitrary unless your dictionaries are
OrderedDict
s. To be memory efficientIn Python 2.x (where
dict.items
andzip
create lists) you can do the following:from itertools import izip for (i, j), (k, v) in izip(d.iteritems(), c.iteritems()): print i, j, k, v
This won't necessarily be faster, as you will observe on small lists it's faster to iterate over these intermediate lists however you will notice a speed improvement when iterating very large data structures.
In Python 3.x
zip
is the same asizip
(which no longer exists) anddict.items
(dict.iteritems
no longer exists) returns a view instead of a list.这篇关于如何在一个循环中翻译两个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!