[英]swap index and value from enumerate()?
Python's enumerate()
returns tuples of index and value: Python的
enumerate()
返回索引和值的元组:
enumerate('abc')
((0,'a'),(1,'b'),(2,'c'))
I'd like to get those tuples in item,index
order ( ('a', 0)
) instead. 我想让这些元组以
item,index
顺序( ('a', 0)
)代替。
How can I do that? 我怎样才能做到这一点?
I'd like to use the reversed tuples to create a dictionary like: 我想使用反向元组来创建像这样的字典:
{'a':0,'b':1,'c':2}
Use dict
comprehension to reverse it: 使用
dict
理解来逆转它:
result = {v: i for i, v in enumerate('abc')}
Addressing @karakfa 's point - this will overwrite potentially repeated elements. 解决@karakfa的问题-这将覆盖可能重复的元素。 If your string was
abca
, the index value assigned for a
will contain 3
, not 0
. 如果您的字符串是
abca
,则为a
分配的索引值将包含3
而不是0
。
One solution is to use the itertools
library: 一种解决方案是使用
itertools
库:
import itertools
dict(zip('abc', itertools.count()))
itertools.count()
is a generator object which generates 0, 1, 2... and the zip
function just ... well zip the two together. itertools.count()
是一个生成器对象,它生成0、1、2 ...,而zip
函数只是...将两者压缩在一起。
There's always good, old-fashioned anonymous functions to do the work for you. 总是有很好的老式匿名函数可以为您完成工作。 It's not the cleanest solution, but it gets the job done.
这不是最干净的解决方案,但可以完成工作。
dict(map(lambda x: (x[1], x[0]), enumerate('abc')))
Another way is to use zip: 另一种方法是使用zip:
>>> s = 'abc'
>>> dict(zip(s, range(len(s))))
{'a': 0, 'b': 1, 'c': 2}
Using a generator: 使用生成器:
>>> dict((v, i) for i, v in enumerate('abc'))
{'a': 0, 'b': 1, 'c': 2}
You can also try with list comprehension : 您也可以尝试使用列表理解:
new_data=((0,'a'),(1,'b'),(2,'c'))
print(tuple([(i[1],i[0])for i in new_data]))
output: 输出:
(('a', 0), ('b', 1), ('c', 2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.