Python array_flip模拟或最好的方式来做到这一点?
是否有用于Python 3.x的array_flip(php)模拟器?Python array_flip模拟或最好的方式来做到这一点?
从
obj = ['a', 'c', 'b' ]
到
{'a': 1, 'c':2, 'b': 3}
您可以使用与dict
构造沿列表解析如下:
>>> obj = [ 'a', 'c', 'b' ]
>>> dict((x, i + 1) for i, x in enumerate(obj))
{'a': 1, 'c': 2, 'b': 3}
正如评论指出的那样,你可以也使用简单的词典理解:
>>> { x: i + 1 for i, x in enumerate(obj) }
{'a': 1, 'c': 2, 'b': 3}
您可以使用dict_comprehension而不是list_comprehension –
'enumerate'有一个'start'参数:'{x:i代表i,x代表枚举(obj,start = 1)}'。 – Bakuriu
谢谢!好而简单) – SlowSuperman
'{i:j + 1 for j,i in enumerate(obj)}' –
当你有两个'a's时会发生什么?最低的指数应该保留还是新的? – Bakuriu