簡體   English   中英

Python-有沒有一種方法可以使用枚舉獲取(str,index)而不是(index,str)?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM