[英]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.我想出了如何使用基本的内置函数来做到这一点,但它有点难看,一旦我发现了
itertools.groupby
,我立即认为我可以使用它并使 function 更简单。 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: 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.注意,首先需要对列表进行排序,以便
groupby
看到要分组的项目彼此相邻。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.