i have sublist
list=[['RD-2','a',120],
['RD-2','b',125],
['RD-2','c',127],
['RD-3','a',120],
['RD-3','b',140],
['RD-5','a',120]]
i want to make seperate sublists in the list based on 1st element of every sublist if its same. The output should be like below
finallist=[
[['RD-2','a',120],['RD-2','b',125],['RD-2','c',127]],
[['RD-3','a',120],['RD-3','b',140]],
['RD-5','a',120]]
i tried in forloop using if condition but its not working. help me
Using itertools.groupby
Ex:
from itertools import groupby
lst=[['RD-2','a',120],['RD-2','b',125],['RD-2','c',127],['RD-3','a',120],['RD-3','b',140],['RD-5','a',120]]
res = [list(v) for i, v in groupby(lst, lambda x: x[0])] #GroupBy first element.
print(res)
Output:
[[['RD-2', 'a', 120], ['RD-2', 'b', 125], ['RD-2', 'c', 127]], [['RD-3', 'a', 120], ['RD-3', 'b', 140]], [['RD-5', 'a', 120]]]
With no requirement for odering, you can use collections.defaultdict
:
from collections import defaultdict
L = [['RD-2','a',120],['RD-2','b',125],['RD-2','c',127],
['RD-3','a',120],['RD-3','b',140],['RD-5','a',120]]
dd = defaultdict(list)
for key, value1, value2 in L:
dd[key].append([value1, value2])
## Python 3.x, use * unpacking
# for key, *values in L:
# dd[key].append(values)
res = [[[key, value] for value in values] for key, values in dd.items()]
print(res)
# [[['RD-2', ['a', 120]], ['RD-2', ['b', 125]], ['RD-2', ['c', 127]]],
# [['RD-3', ['a', 120]], ['RD-3', ['b', 140]]],
# [['RD-5', ['a', 120]]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With