简体   繁体   English

如何使用 `enumerate` 迭代 `dict` 并解压索引、键和值以及迭代

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

How to iterate dict with enumerate such that I could unpack the index, key and value at the time of iteration?如何使用enumerate迭代dict以便我可以在迭代时解压索引、键和值?

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的字典中的键和值并对它们进行计数,这样我就知道什么时候到了最后一个。

Instead of using mydict , you should be using mydict.items() with enumerate as:而不是使用mydict ,你应该使用mydict.items() with enumerate as:

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

Explanation:解释:

  • enumerate() returns an iterator object which contains tuples in the format: [(index, list_element), ...]enumerate()返回一个迭代器对象,它包含以下格式的元组: [(index, list_element), ...]
  • dict.items() returns an iterator object (in Python 3.x. It returns list in Python 2.7) in the format: [(key, value), ...] dict.items()返回一个迭代器对象(在 Python 3.x 中。它在 Python 2.7 中返回list ,格式为: [(key, value), ...]
  • On combining together, enumerate(dict.items()) will return an iterator object containing tuples in the format: [(index, (key, value)), ...]组合在一起时, enumerate(dict.items())将返回一个包含以下格式的元组的迭代器对象: [(index, (key, value)), ...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM