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

Answers


You could use 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']]

To group lines based on the value of the first space-separated column:

from collections import defaultdict

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

Need Your Help

How to convert a native binary image in memory to an Winforms Image?

winforms image c++-cli native

I have a native c++ library that creates an output image as a native area in memory. It's ARGB, 32bit for one pixel, width*height times. I have a winforms application where I want to display this o...

Images in case of multi screen support in android

android android-screen-support

I have confusion regarding multi screens support in android. I have gone through article for multi screen support at android developer forum. My question is if app has 15-20 images that need to be ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.