简体   繁体   English

Python同时循环,枚举并添加到字典中

[英]Python simultaneously loop, enumerate, and add to a dictionary

Is there a neat way to loop through a list, adding the value as a dictionary key, and its position in the list as its value? 有没有一种巧妙的方法来遍历列表,将值添加为字典键,并将其在列表中的位置添加为其值? something like: 就像是:

for x,y in enumerate(line):
    dictItem[x] = y

but in one line? 但在一排?

You can simply feed the enumerate to the dict constructor: 您可以简单地将枚举输入到dict构造函数中:

dictItem = dict(enumerate(line))

dict(..) can construct a dictionary when you give it an iterable of 2-tuples that contain the key and the value . dict(..)赋予包含value的2元组可迭代的字典时,它可以构造一个字典。 Your enumerate(..) generates tuples with that key and value. 您的enumerate(..)生成具有该键和值的元组。

In case you want to update the dictionary (ie add new values or update the existing ones), you can write: 如果要更新字典(即添加新值或更新现有值),可以编写:

dictItem.update(enumerate(line))

You can try: 你可以试试:

dictItem.update(enumerate(line))

For example: 例如:

>>> a = {}
>>> a.update(enumerate([4, 5, 6]))
>>> a
{0: 4, 1: 5, 2: 6}

Try this, 尝试这个,

{pos:val for pos,val in enumerate(line)}

Exicution, 兴奋,

In [6]: line = [7,6,5,4,4]    
In [7]: {pos:val for pos,val in enumerate(line)}
Out[7]: {0: 7, 1: 6, 2: 5, 3: 4, 4: 4}

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

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