0
l=[[15.0, 10265.0, 1860.0, 142600.0, 3],[12.0, 14631.0, 3298.0, 153100.0, 2],[22.0, 1707.0, 296.0, 126600.0, 3],[7.0, 1737.0, 290.0, 147000.0, 2]]


If i want to get two lists:

[[15.0, 10265.0, 1860.0, 142600.0, 3],[22.0, 1707.0, 296.0, 126600.0, 3]] [[12.0, 14631.0, 3298.0, 153100.0, 2],[7.0, 1737.0, 290.0, 147000.0, 2]]

how do i do this using itertools? is there any other way to do this?

l1=[]
key_func = lambda x: x[-1]
for key, group in itertools.groupby(l, key_func):
     l1.append(list(group))

I tried this but i got [[[15.0, 10265.0, 1860.0, 142600.0, 3]], [[12.0, 14631.0, 3298.0, 153100.0, 2]], [[22.0, 1707.0, 296.0, 126600.0, 3]], [[7.0, 1737.0, 290.0, 147000.0, 2]]]

  • `groupby` requires the input to be sorted (in terms of your key function). See: https://stackoverflow.com/questions/773/how-do-i-use-itertools-groupby – slothrop Mar 25 '23 at 09:25

3 Answers3

1

groupby only works if the input is sorted by the grouping key, otherwise a simple dict will work just fine:

groups = {}

for item in YOUR_LIST:
    groups.setdefault(item[-1], []).append(item)

grouped = list(groups.values())
gog
  • 10,367
  • 2
  • 24
  • 38
0

You can achive what you want without even using itertools:

l = [[15.0, 10265.0, 1860.0, 142600.0, 3], [12.0, 14631.0, 3298.0, 153100.0, 2], [22.0, 1707.0, 296.0, 126600.0, 3], [7.0, 1737.0, 290.0, 147000.0, 2]]

list_with3 = [x for x in l if x[-1] == 3]
list_with2 = [x for x in l if x[-1] == 2]

print(list_with3)
print(list_with2)

The code that I provided uses list comprehensions to generate two distinct lists. First with the ending 3 and other with the ending 2.

ahmedg
  • 309
  • 1
  • 2
  • 12
  • 1
    Suppose that the last element of each sublist could be any number from 0 to 1000. How would you adapt the code for that? – slothrop Mar 25 '23 at 09:23
0

You would need to sort the list on that grouping key for grouby to work as expected:

l=[[15.0, 10265.0, 1860.0, 142600.0, 3],[12.0, 14631.0, 3298.0, 153100.0, 2],
   [22.0, 1707.0, 296.0, 126600.0, 3],[7.0, 1737.0, 290.0, 147000.0, 2]]

from itertools import groupby
key_func = lambda x: x[-1]
l1 = [g for _,(*g,) in groupby(sorted(l,key=key_func),key_func) ]

print(l1)
[[[12.0, 14631.0, 3298.0, 153100.0, 2], [7.0, 1737.0, 290.0, 147000.0, 2]],
 [[15.0, 10265.0, 1860.0, 142600.0, 3], [22.0, 1707.0, 296.0, 126600.0, 3]]]

If you don't want to sort the list, you can use a dictionary to form the groups and convert its values() into a list at the end:

g = dict()
g.update( (s[-1],g.get(s[-1],[])+[s]) for s in l )
l1 = list(g.values())

print(l1)
[[[15.0, 10265.0, 1860.0, 142600.0, 3], [22.0, 1707.0, 296.0, 126600.0, 3]], 
 [[12.0, 14631.0, 3298.0, 153100.0, 2], [7.0, 1737.0, 290.0, 147000.0, 2]]]
Alain T.
  • 40,517
  • 4
  • 31
  • 51