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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:22:05  来源:igfitidea点击:

How to iterate `dict` with `enumerate` and unpack the index, key, and value along with iteration

pythondictionary

提问by themink

How to iterate dictwith enumeratesuch that I could unpack the index, key and value at the time of iteration?

如何迭代dictenumerate以便我可以在迭代时解压索引、键和值?

Something like:

就像是:

for i, (k, v) in enumerate(mydict):
    # some stuff

I want to iterate through the keys and values in a dictionary called mydictand 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 enumerateas:

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:

说明:

  • enumeratereturns an iterator object which contains tuples in the format: [(index, list_element), ...]
  • dict.items()returns an iterator object (in Python 3.x. It returns listin 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)), ...]