enumerate()用于python中的字典 [英] enumerate() for dictionary in python
本文介绍了enumerate()用于python中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们使用enumerate
来迭代列表,但是我在字典中对其进行了尝试,但没有给出错误.
I know we use enumerate
for iterating a list but I tried it in a dictionary and it didn't give an error.
代码:
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
print(i, j)
输出:
0 0
1 1
2 2
3 4
4 5
5 6
6 7
有人可以解释输出吗?
推荐答案
在已经提供的答案之上,Python中有一个非常好的模式,允许您枚举字典的键和值.
On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.
通常情况下,您枚举字典的键:
example_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
哪个输出:
0 1
1 2
2 3
3 4
但是,如果您想通过键和值进行枚举,则可以这样:
But if you want to enumerate through both keys and values this is the way:
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
哪个输出:
0 1 a
1 2 b
2 3 c
3 4 d
这篇关于enumerate()用于python中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文