Modify list with python by index value
I have browsed similar threads a lot, but maybe due my lack of knowledge in python, I haven't found a working solution in my problem.
This is part of the code:
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)
the output of "both" looks like this 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']
I would like to reserve lines / cells with the same index value. Like in this case:
['Fam_c828_1', '12-0799NK', '100'] ['Fam_c828_1', '12-0800TK', '100']
and the rest would be removed to another list.
Thanks in advance
You could use itertools.groupby:
>>> from itertools import groupby >>> groups = groupby(both, lambda x: x) # 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) # Cast the group iterable into a list for display purposes [['Fam_c828_1', '12-0799NK', '100'], ['Fam_c828_1', '12-0800TK', '100']]
To group lines based on the value of the first space-separated column:
from collections import defaultdict d = defauldict(list) # index -> line for line in splitline: columns = line.split() d[columns].append(columns)