简体   繁体   中英

group by unique column values in list using Python

I have a list with column namely A,B,C,D and I wanted to reformat list by a group of Unique D column's values. List

列出图片

Expected Output:

list=[d1[[1,11,n1],[1,22,n2]],d2[[3,33,n3]]

and then print all list under d1:

[1,11,n1],[1,22,n2]

You can use operator.itemgetter() to extract the field of interest (field 3 is the D column). Then use itertools.groupby() to extract groups with a common key:

>>> from operator import itemgetter
>>> from itertools import groupby
>>> data = [ [1, 11,'n1','d1'],
         [2, 22, 'n2', 'd1'],
         [3, 33, 'n3', 'd2'],
]
>>> data.sort(key=itemgetter(3))   # sort by column d
>>> result = []
>>> for k, groups in groupby(data, key=itemgetter(3)):
        entry = [group[:-1] for group in groups]
        result.append((k, entry))

>>> result
[('d1', [[1, 11, 'n1'], [2, 22, 'n2']]), ('d2', [[3, 33, 'n3']])]

If you just want to print the d1 groups, the code is even simpler:

>>> for k, groups in groupby(data, key=itemgetter(3)):
        if k == 'd1':
            print([group[:-1] for group in groups])

[[1, 11, 'n1'], [2, 22, 'n2']]

The code [group[:-1] for group in groups] uses slicing and a list comprehension to remove the key-field as shown in your expected output.

Hope this helps :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM