Reputation: 1081
I have a list and want to split it based on unique values of its last column in python. This is my list:
pnt=[[1.,2.,4.,'AA'], [0.,0.,0.,'AA'], [2.,1.,0.,'AA'],\
[0.,-3.,1.,'BB'], [2.,5.,8.,'BB'], [.1,3.,0.,'CC']]
I want to get it as:
pnt=[[[1.,2.,4.,'AA'], [0.,0.,0.,'AA'], [2.,1.,0.,'AA']],\
[[0.,-3.,1.,'BB'], [2.,5.,8.,'BB']], [[.1,3.,0.,'CC']]]
I read this solution but still cannot solve my issue.
Upvotes: 1
Views: 1290
Reputation: 140307
itertools.groupby
is the function you need. It needs to be customized to check key from the fourth element of each list.
Then elements and the return value itself needs to be forced to list
to see the actual result (else it's optimized as generator functions). We discard the key (with _
) because we're only interested in the elements, not the value that was used to group them.
import itertools
pnt=[[1.,2.,4.,'AA'], [0.,0.,0.,'AA'], [2.,1.,0.,'AA'],\
[0.,-3.,1.,'BB'], [2.,5.,8.,'BB'], [.1,3.,0.,'CC']]
print([list(x) for _,x in itertools.groupby(pnt,lambda x:x[3])])
result:
[[[1.0, 2.0, 4.0, 'AA'], [0.0, 0.0, 0.0, 'AA'], [2.0, 1.0, 0.0, 'AA']],
[[0.0, -3.0, 1.0, 'BB'], [2.0, 5.0, 8.0, 'BB']],
[[0.1, 3.0, 0.0, 'CC']]]
note that this method will group the consecutive groups only.
Upvotes: 2
Reputation: 82795
You can use a dict
to get the desired output.
Ex:
pnt=[[1.,2.,4.,'AA'], [0.,0.,0.,'AA'], [2.,1.,0.,'AA'],\
[0.,-3.,1.,'BB'], [2.,5.,8.,'BB'], [.1,3.,0.,'CC']]
result = {}
for i in pnt:
result.setdefault(i[-1], []).append(i) # Form Dict with key as last value from list and value as the list
print(list(result.values())) # Get Values of Dict
Output:
[[[1.0, 2.0, 4.0, 'AA'], [0.0, 0.0, 0.0, 'AA'], [2.0, 1.0, 0.0, 'AA']],
[[0.0, -3.0, 1.0, 'BB'], [2.0, 5.0, 8.0, 'BB']],
[[0.1, 3.0, 0.0, 'CC']]]
Upvotes: 2