Python 如何使用 `enumerate` 迭代 `dict` 并随着迭代解压索引、键和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42193712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate `dict` with `enumerate` and unpack the index, key, and value along with iteration
提问by themink
How to iterate dict
with enumerate
such that I could unpack the index, key and value at the time of iteration?
如何迭代dict
,enumerate
以便我可以在迭代时解压索引、键和值?
Something like:
就像是:
for i, (k, v) in enumerate(mydict):
# some stuff
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
并计算它们,所以我知道我什么时候在最后一个。
回答by Moinuddin Quadri
Instead of using mydict
, you should be using mydict.items()
with enumerate
as:
mydict
您应该使用mydict.items()
withenumerate
作为,而不是使用:
for i, (k, v) in enumerate(mydict.items()):
# your stuff
Sample example:
示例:
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
Explanations:
说明:
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
返回一个迭代器对象,其中包含以下格式的元组:[(index, list_element), ...]
dict.items()
以以下格式返回一个迭代器对象(在 Python 3.x 中。它list
在 Python 2.7 中返回):[(key, value), ...]
- 组合在一起时,
enumerate(dict.items())
将返回一个包含以下格式元组的迭代器对象:[(index, (key, value)), ...]