2014-01-08 40 views
2

我想從迭代中檢索特定索引。這將相當於:解壓縮特定索引

In [7]: def f(): 
    ...:  return [1,2,3,4,5] 
In [8]: (_, x, _, y, _) = f() 
In [9]: x, y 
Out[9]: (2, 4) 

但我不想計算迭代多次或者是很長,我不想寫太多_小號

我的問題是純粹出於好奇心,我實際上使用了一個局部變量,如上所示。

編輯

一種解決方案是簡單地使用與符號iterable[start:end:step]切片:

In [24]: (x, y) = f()[1:4:2] 
In [25]: x, y 
Out[25]: (2, 4)` 

EDDIT BIS:如果您需要檢索每n th元素 使用切片工程一個迭代,但如果你想索引2,35,6使用operator.itemgetter(2,3,5,6)(lst)元素似乎是一個更好的解決方案:

In [8]: operator.itemgetter(2,3,5,6)(range(10)) 
Out[8]: (2, 3, 5, 6) 
+1

如果你知道你想要的索引,爲什麼不使用切片? – MattDMo

+0

你有沒有嘗試過嗎? – Totem

+0

@MattDMo切片可以完美工作,如果使用'iterable [start:end:step]'符號,甚至可以用於非連續索引。謝謝你沒有想到它! – bvidal

回答

2

一個稍微迂迴的方式是使用itemgetter函數從operator模塊。

import operator 
m = operator.itemgetter(2,3) 
x, y = m([1,2,3,4,5]) 

itemgetter的呼叫創建一個可調用這需要一個可迭代L並返回L[2]L[3]