[英]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)]? 有没有办法代替[['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
. 我将i, test
从i, test1
更改为i, test1
。
And I switched (i,test1)
to (test1,i)
. 然后我将(i,test1)
切换为(test1,i)
。
Aside from the obvious genexpr/listcomp wrapper: 除了显而易见的genexpr / listcomp包装器之外:
# 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: 您可以使用map
(在future_builtins.map
上为future_builtins.map)和operator.itemgetter
在C层进行逆转,以提高速度:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.