本文介绍了如何使用enumerate迭代dict并解压缩索引,键和值以及迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用enumerate
迭代dict
,以便在迭代时可以解开索引,键和值?
How to iterate dict
with enumerate
such that I could unpack the index, key and value at the time of iteration?
类似的东西:
for i, (k, v) in enumerate(mydict):
# some stuff
我想遍历一本名为mydict
的词典中的键和值,并对它们进行计数,所以我知道我何时读到最后一个.
I want to iterate through the keys and values in a dictionary called mydict
and count them, so I know when I'm on the last one.
推荐答案
您应该使用 mydict.items()
与 enumerate
如:
Instead of using mydict
, you should be using mydict.items()
with enumerate
as:
for i, (k, v) in enumerate(mydict.items()):
# your stuff
示例:
mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
print("index: {}, key: {}, value: {}".format(i, k, v))
# which will print:
# -----------------
# index: 0, key: 1, value: a
# index: 1, key: 2, value: b
说明:
-
enumerate
返回一个迭代器对象,该对象包含格式为[(index, list_element), ...]
的元组. -
dict.items()
返回迭代器对象(在Python 3.x中.在Python 2.7中返回list
),格式为:[(key, value), ...]
- 组合在一起时,
enumerate(dict.items())
将返回一个迭代器对象,该对象包含格式为[(index, (key, value)), ...]
的元组.
enumerate
returns an iterator object which contains tuples in the format:[(index, list_element), ...]
dict.items()
returns an iterator object (in Python 3.x. It returnslist
in Python 2.7) in the format:[(key, value), ...]
- On combining together,
enumerate(dict.items())
will return an iterator object containing tuples in the format:[(index, (key, value)), ...]
这篇关于如何使用enumerate迭代dict并解压缩索引,键和值以及迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!