2017-03-16 37 views

回答

1

除了明顯genexpr/listcomp包裝:

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

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

你可以使用mapfuture_builtins.map上的Py2)和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)) 
1

用途:

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

我做了修復一個小錯字你在開始的代碼了。我將i, test更改爲​​。

而且我將(i,test1)轉換爲(test1,i)

+0

如果你正在開箱和重新包裝,只需按相反順序重新包裝,並跳過切片... – ShadowRanger

+0

哦,是的......那會讓更多感。更新。 – Neil

1

您可以簡單地在列表理解語句中切換變量。

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

結果:

[('test', 0), ('test2', 1), ('test3', 2)] 
相關問題