简体   繁体   中英

Python - Is there a way to get (str, index) instead of (index, str) using enumerate?

For example,

test = ["test1", "test2", "test3"]
print ([(i, test) for i, test in enumerate(test)])
>> [(0, 'test1'), (1, 'test2'), (2, 'test3')]

Is there a way to instead get [('test', 0), ('test2', 1), ('test3', 2)]?

Use:

test = ["test", "test2", "test3"]
print ([(test1, i) for i, test1 in enumerate(test)])

I did fix a minor typo you had in your beginning code. I changed i, test to i, test1 .

And I switched (i,test1) to (test1,i) .

Aside from the obvious genexpr/listcomp wrapper:

# Lazy
((x, i) for i, x in enumerate(test))

# Eager
[(x, i) for i, x in enumerate(test)]

you could use map ( future_builtins.map on Py2) and operator.itemgetter to do the reversal at the C layer for extra speed:

from future_builtins import map  # Only on Py2, to get Py3-like generator based map

from operator import itemgetter

# Lazy, wrap in list() if you actually need a list, not just iterating results
map(itemgetter(slice(None, None, -1)), enumerate(test))

# More succinct, equivalent in this case, but not general reversal
map(itemgetter(1, 0), enumerate(test))

you can simply switch the variables in the list comprehension statement.

test = ["test", "test2", "test3"]
print ([(test,i) for (i,test) in enumerate(test)])

result:

[('test', 0), ('test2', 1), ('test3', 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