[英]Transforming list to dict with list items as keys and list indices as values in python
I want to transform 我想改造
l = ['a','b','c','d']
to 至
d = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
The best solution I have so far is that one: 我到目前为止最好的解决方案是:
d = {l[i]:i for i in range(len(l))}
Is there more elegant way to do this? 有没有更优雅的方式来做到这一点?
d = {e:i for i, e in enumerate(l)}
编辑:正如@LeonYoung建议的那样,如果你想与python <2.7兼容(尽管有标签),你必须使用
d = dict((e, i) for i, e in enumerate(l))
With itertools
, just for fun 使用
itertools
,只是为了好玩
>>> from itertools import count, izip
>>> L = ['a', 'b', 'c', 'd']
>>> dict(izip(L, count()))
{'a': 0, 'c': 2, 'b': 1, 'd': 3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.