简体   繁体   中英

Attempting to use itertools.groupby

So basically I have this list of tuples,like this

list1 = [(1, 0.3), (2, 0.0), (3, 0.5), (4, 0.1), (5, 0.7), (6, 0.5), (7, 0.0), (8, 0.3)]

And I was trying to organise it into sublists where every sublist has every tuple with the same second value, like this

list1 = [[0.0, (2, 0.0), (7, 0.0)], [0.1, (4, 0.1)], [0.3, (1, 0.3), (8, 0.3)], [0.5, (3, 0.5), (6, 0.5)], [0.7, (5, 0.7)]]

With the value they're organized around being the first value in each sublist.

I figured how to do this with basic built-in functions, but it's kinda ugly and once I found out about itertools.groupby I immediately thought I could use it and make the function simpler. The problem is I can't really get it to work. Can this method even be used for this type of problem or am I just not understanding how to use it?

You could use something like this:

list1 = [(1, 0.3), (2, 0.0), (3, 0.5), (4, 0.1), (5, 0.7), (6, 0.5), (7, 0.0), (8, 0.3)]
d = {k[1] : [] for k in list1}
for item in list1:
    d[item[1]].append(item)
output = sorted([[k] + v for k, v in d.items()])
print(output)

Output:

[[0.0, (2, 0.0), (7, 0.0)], 
 [0.1, (4, 0.1)], 
 [0.3, (1, 0.3), (8, 0.3)], 
 [0.5, (3, 0.5), (6, 0.5)], 
 [0.7, (5, 0.7)]]

Try:

from itertools import groupby
from operator import itemgetter

list1 = [(1, 0.3), (2, 0.0), (3, 0.5), (4, 0.1), (5, 0.7), (6, 0.5), (7, 0.0), (8, 0.3)]

output = [[k, *g] for k, g in groupby(sorted(list1, key=itemgetter(1)), key=itemgetter(1))]
print(output)
# [[0.0, (2, 0.0), (7, 0.0)], [0.1, (4, 0.1)], [0.3, (1, 0.3), (8, 0.3)], [0.5, (3, 0.5), (6, 0.5)], [0.7, (5, 0.7)]]

Note that you first need to sort the list, so that the groupby sees that the items to be grouped are adjacent to each other.

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