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.