Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group the sublist seperatly inside the list based on condition in python

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

like image 513
learningstudent Avatar asked Sep 06 '25 03:09

learningstudent


2 Answers

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]]]
like image 150
Rakesh Avatar answered Sep 07 '25 20:09

Rakesh


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]]]]
like image 32
jpp Avatar answered Sep 07 '25 21:09

jpp