简体   繁体   中英

Python itertools.groupby() using tuples with multiple keys

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM