如何在一个循环中翻译两个字典? [英] How to travese two dictionaries in a single for loop?

查看:221
本文介绍了如何在一个循环中翻译两个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想产生以下效果:

 对于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 
for i,j),(k,v)in izip(d.iteritems(),c.iteritems()):
print i,j,k,v
/ pre>

这不一定会更快,因为您将在小列表中观察到,迭代这些中间列表的速度更快,但是您会注意到在重复迭代时的速度提升大数据结构



在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 OrderedDicts. To be memory efficient

In Python 2.x (where dict.items and zip 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 as izip (which no longer exists) and dict.items (dict.iteritems no longer exists) returns a view instead of a list.

这篇关于如何在一个循环中翻译两个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆