简体   繁体   中英

swap index and value from enumerate()?

Python's enumerate() returns tuples of index and value:

enumerate('abc')
((0,'a'),(1,'b'),(2,'c'))

I'd like to get those tuples in item,index order ( ('a', 0) ) instead.

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:

result = {v: i for i, v in enumerate('abc')}

Addressing @karakfa 's point - this will overwrite potentially repeated elements. If your string was abca , the index value assigned for a will contain 3 , not 0 .

One solution is to use the itertools library:

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.

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:

>>> 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM