2013-05-03 56 views
0

我瀏覽過類似的線程很多,但可能是由於我對python缺乏知識,我還沒有在我的問題中找到工作解決方案。用python按索引[0]值修改列表

這是代碼的一部分:

for line in splitline: 
    if("Fam" in line): 
     if("NK" in line or "V" in line): 
      normaali = line.split() 
      normaalilista.append(normaali) 
      both.append(normaali) 
     if("TK" in line): 
      tumor = line.split() 
      tuumorilista.append(tumor) 
      both.append(tumor) 

「的輸出均爲」看起來像這樣大氣壓:

['Fam_c828_1', '12-0799NK', '100'] 
['Fam_c828_1', '12-0800TK', '100'] 
['Fam_s56_1', '12-0801TK', '100'] 
['Fam_s134_1', '12-0802NK', '100'] 
['Fam_s146_1', '12-0803TK', '100'] 

我想保留線/細胞具有相同索引[0 ]值。就像在這種情況下一樣:

['Fam_c828_1', '12-0799NK', '100'] 
['Fam_c828_1', '12-0800TK', '100'] 

其餘的將被刪除到另一個列表。

在此先感謝

+0

相關:HTTP:// stackoverflow.com/questions/16349097/python-nested-list-modification – 2013-05-03 11:49:27

回答

1

你可以使用itertools.groupby

>>> from itertools import groupby 
>>> groups = groupby(both, lambda x: x[0]) # Group `both` by the zeroth index of its members 
>>> group = next(groups) # Get the first group in groups 
>>> group 
('Fam_c828_1', <itertools._grouper object at 0x10f065d10>) 
>>> list(group[1]) # Cast the group iterable into a list for display purposes 
[['Fam_c828_1', '12-0799NK', '100'], ['Fam_c828_1', '12-0800TK', '100']] 
+1

注意:'groupby'預計'both'會按'x [0]排序' – jfs 2013-05-04 00:08:52

+0

這個效果非常好。它目前打印出第一組比賽。我如何能夠通過索引[0]打印出所有可能的匹配。謝謝! – jester112358 2013-05-06 06:12:27

+0

@ jester112358通過迭代'groupby'返回的生成器。每次迭代都會返回一個形式爲'(groupkey,group)'的元組。 – kojiro 2013-05-06 14:03:28

1

要基於第一空間分隔列的值組線:

from collections import defaultdict 

d = defauldict(list) # index[0] -> line 
for line in splitline: 
    columns = line.split() 
    d[columns[0]].append(columns) 
+0

需要玩一下,但似乎做我的要求。謝謝! – jester112358 2013-05-03 12:13:49