[英]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.