2014-04-11 109 views

回答

1

你可以用它做如下:

b = [1,0,3,5] 
x = [a[i] for i in b] 

>>> x 
[10, 0, 30, 50] 

,你說你不想導入任何軟件包。

2

您可以使用operator.itemgetter,這樣

from operator import itemgetter 
print itemgetter(1, 0, 3, 5)(a) 
# (10, 0, 30, 50) 

你甚至可以在這個變量存儲後來就用這個。例如,

custom_picker = itemgetter(1, 0, 3, 5) 
custom_picker(a) 
+1

這可能會比@ sshashank124的解決方案更快,因爲'operator'是用C語言實現的,所以'itemgetter'可能會超越Python循環。 –

+0

我接受了sshashank124的回答,因爲它不需要導入,但是這很好理解,謝謝!儘管一個缺點是爲了獲得一個列表,似乎必須編寫:'list(itemgetter(1,0,3,5)(a))''。 – andreasdr

+0

@andreasdr我不知道你的用例是什麼,但實際上元組和列表幾乎是一樣的(除了元組是不可變的事實除外) – thefourtheye