ov7*_*v7a 2 python dictionary list python-2.7
我想改造
l = ['a','b','c','d']
Run Code Online (Sandbox Code Playgroud)
至
d = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
Run Code Online (Sandbox Code Playgroud)
我到目前为止最好的解决方案是:
d = {l[i]:i for i in range(len(l))}
Run Code Online (Sandbox Code Playgroud)
有没有更优雅的方式来做到这一点?
d = {e:i for i, e in enumerate(l)}
Run Code Online (Sandbox Code Playgroud)
编辑:正如@LeonYoung建议的那样,如果你想与python <2.7兼容(尽管有标签),你必须使用
d = dict((e, i) for i, e in enumerate(l))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |