[英]Python - Is there a way to get (str, index) instead of (index, str) using enumerate?
例如,
test = ["test1", "test2", "test3"]
print ([(i, test) for i, test in enumerate(test)])
>> [(0, 'test1'), (1, 'test2'), (2, 'test3')]
有没有办法代替[['test',0),('test2',1),('test3',2)]?
采用:
test = ["test", "test2", "test3"]
print ([(test1, i) for i, test1 in enumerate(test)])
我确实修复了起始代码中的一个小错字。 我将i, test
从i, test1
更改为i, test1
。
然后我将(i,test1)
切换为(test1,i)
。
除了显而易见的genexpr / listcomp包装器之外:
# Lazy
((x, i) for i, x in enumerate(test))
# Eager
[(x, i) for i, x in enumerate(test)]
您可以使用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))
您只需在列表理解语句中切换变量即可。
test = ["test", "test2", "test3"]
print ([(test,i) for (i,test) in enumerate(test)])
结果:
[('test', 0), ('test2', 1), ('test3', 2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.