簡體   English   中英

使用python按index [0]值修改列表

[英]Modify list with python by index[0] value

我已經瀏覽了很多類似的線程,但也許由於我對python缺乏了解,我還沒有在我的問題中找到一個可行的解決方案。

這是代碼的一部分:

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)

“both”的輸出看起來像這個atm:

['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']

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

提前致謝

要根據第一個以空格分隔的列的值對行進行分組:

from collections import defaultdict

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

你可以使用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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM