[英]How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one?
[英]How to create a dictionary where the keys are the elements in a list and the values are numbers from 1 to n?
假設我有一個列表l1 = [a,b,c,d,e],我想將其映射到包含以下{a:1,b:2,c:3,d:4, E:5}
我知道如何以一種非常幼稚的方式做到這一點,但是我想要更多的“ pythonic”
天真的方法:
dic = {}
j = 1
for i in list1:
dic[i] = j
j += 1
如何使用字典理解:
>>> {v: k for k, v in enumerate(l1, 1)}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
只是為了彌補之前的麻煩,您可以將dict
類型的構造函數與itertools.count
和zip
:
>>> L1 = ['a','b','c','d']
>>> from itertools import count
>>> dict(zip(L1, count(1)))
{'c': 3, 'b': 2, 'a': 1, 'd': 4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.