2013-06-21 61 views
3

我試圖得到一個清單,從索引中另一個列表中的特定輸出, 例如:Python列表理解多變量

L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)] 
multiple_index = [entry[0, 3, 4] for entry in L] 
#----> I know this specific code is wrong 

如果上面的代碼可以輸出我喜歡它,

[(0, 3, 4), (6, 9, 10), (...etc)] 

我想從主列表中的每個指標的個別分項指數進行分組如圖所示,如果這是在所有可能的,而且我想我可以使用什麼樣的代碼才能正常退出這個功能,謝謝。

編輯: 另外,我怎樣才能格式化它顯示爲行乾淨,我輸出它們到一個文本文件使用.writelines和一個單獨的輸出行,再次感謝!

+0

你的編輯,使這個已經有很多答案對SO另一個問題。 –

+0

這很有趣,對不起,我沒有找到其他地方的原始問題的答案,編輯只是要求一個額外的幫助,就是這樣。 – ImmortalxR

回答

8

使用operator.itemgetter()

from operator import itemgetter 

multiple_index = map(itemgetter(0, 3, 4), L) 

或列表中的理解:

multiple_index = [itemgetter(0, 3, 4)(i) for i in L] 
+0

這很奇妙,作爲一個快速拋開,如果你能回答這個問題,我怎麼能得到multiple_index顯示輸出在單獨的行,我編輯原始文章:) – ImmortalxR

+1

您可以使用'str.join()'將列表連接到字符串:''\ n'.join([',',join(i)for i in multiple_index])'for一個字符串通過換行符連接外部列表,內部列表通過逗號連接。 –

+0

當我應用上述代碼時,它給了我一個無效的語法錯誤?任何想法爲什麼? – ImmortalxR

3

這裏有一個選項:

L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)] 
multiple_index = [(entry[0], entry[3], entry[4]) for entry in L] 

或者使用operator.itemgetter()

from operator import itemgetter 
indices = itemgetter(0, 3, 4) 
multiple_index = [indices(entry) for entry in L] 
+0

是 - 'operator.itemgetter'就是我想去... –

2

您對此感興趣嗎?

L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)] 
multiple_index = [(entry[0], entry[3], entry[4]) for entry in L] 
#----> I know this specific code is wrong 
2
from operator import itemgetter 
get = itemgetter(0, 3, 4) 
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)] 
multiple_index = [get(entry) for entry in L] 

一個更實用的風格:

multiple_index = map(itemgetter(0, 3, 4), L) 

當然,如果你使用numpy的,你可以不喜歡以下:

import numpy as np 
L = np.array([(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)]) 
multiple_index = L[:,(0, 3, 4)] 

導致:

array([[ 0, 3, 4], 
     [ 6, 9, 10], 
     [11, 14, 15]]) 

就我個人而言,我最喜歡numpy版本,但這需要你安裝numpy。這裏有一些更多的numpy的索引,如果你有興趣:http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

numpy的也有花式切片和使用np.s_np.r_np.c_範圍建設一些巧妙的快捷方式/技巧。

2

只是一些多樣性,這裏是用itertools.compress的方式,

>>> from itertools import compress, count 
>>> indices = {0,3,4} 
>>> items_at = lambda indices: (1 if n in indices else 0 for n in count()) 
>>> [tuple(compress(e, items_at(indices))) for e in L] 
[(0, 3, 4), (6, 9, 10)] 
0

列表元組和dictioonary查找使用的是他們的GetItem方法

myarray=[0,1,2] 
print myarray[1] 
#result:1 
#equivalent to 
print myarray.__getitem__(1) 

可以映射您完成想要的指標實現每個列表的getitem函數。這將返回一個列表,其中包含每個列表的這些索引處的項目。修改您的示例代碼:

L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)] 
multiple_index = [map(entry.__getitem__,[0, 3, 4]) for entry in L] 

這會產生所需的輸出。

更多Python的魔術方法看this

0

這裏是我會怎麼做:

L=[tuple(range(0,6*1)),tuple(range(6*1,6*2)),tuple(range(6*2,6*3))] 
    print [tuple(map(lambda i: entry[i],[0,3,4])) for entry in L]