1

I'm trying to read through a tuple and sort it. I want to group by the first word in the lists, and keep the lists with the smallest third word. Then I want it to return the entire list for those that were kept.

I found a very useful example here, except I'm looking to do this with lists with three words, instead of two.

The current output I'm getting is:

grape 3
apple 4
banana 1

The output I would like is:

grape lemon 3
apple banana 4
banana pie 1

I'm really just looking to get that second word from the lists. How can I do this?

import itertools
import operator

L = [('grape', 'orange', 100), ('grape', 'lemon', 3), ('apple', 'kiwi', 15), 
    ('apple', 'pie', 10), ('apple', 'banana',4), ('banana', 'pie', 1), 
    ('banana', 'kiwi', 2)]

it = itertools.groupby(L, operator.itemgetter(0))
for key, subiter in it:
    print(key, min(item[2] for item in subiter))
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
Kelsey
  • 401
  • 9
  • 21

1 Answers1

4

It looks like you problem is not related to itertools.groupby, but to min.

To recover the tuple with smallest third value, use the key argument of the min function.

import itertools
import operator

L = [('grape', 'orange', 100), ('grape', 'lemon', 3), ('apple', 'kiwi', 15),
    ('apple', 'pie', 10), ('apple', 'banana',4), ('banana', 'pie', 1),
    ('banana', 'kiwi', 2)]

it = itertools.groupby(L, operator.itemgetter(0))

for key, group in it:
    print(*min(group, key=operator.itemgetter(2))) # Use the key argument of min

Output

grape lemon 3
apple banana 4
banana pie 1
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73