如何在python中使用enumerate()枚举字典中的项目 [英] How to enumerate items in a dictionary with enumerate( ) in python

查看:72
本文介绍了如何在python中使用enumerate()枚举字典中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我想在python中枚举键及其值(不带方括号).我尝试了以下代码:

As the title suggests I wanted to enumerate the key and its values (without brackets) in python. I tried the following code :

example_dict = {'left':'<','right':'>','up':'^','down':'v',}
[print(i,j,a) for (i,j,a) in enumerate(example_dict.items())]

但是它不起作用.我希望输出像这样

But it doesn't work. I want the output to be like this

0 left <
1 right >
2 up ^
3 down v

提前谢谢

推荐答案

在这种情况下,枚举返回(index,(key,value)),因此您只需要将拆包更改为对于i,(j,a),尽管我个人会使用 k,v 代替示例中的 j,a .

In this case enumerate returns (index, (key, value)), so you just need to change your unpacking to for i, (j, a), though personally I would use k, v instead of j, a in an example.

for i, (k, v) in enumerate(example_dict.items()):
    print(i, k, v)

顺便说一句,不要对任何副作用都理解;只需使用for循环即可.

BTW, don't use a comprehension for side effects; just use a for-loop.

这篇关于如何在python中使用enumerate()枚举字典中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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