itertools.groupby()无法正确分组 [英] itertools.groupby() not grouping correctly

查看:87
本文介绍了itertools.groupby()无法正确分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

self.data = [(1, 1, 5.0),
             (1, 2, 3.0),
             (1, 3, 4.0),
             (2, 1, 4.0),
             (2, 2, 2.0)]

当我运行此代码时:

for mid, group in itertools.groupby(self.data, key=operator.itemgetter(0)):

对于list(group),我得到:

[(1, 1, 5.0),
 (1, 2, 3.0),
 (1, 3, 4.0)]

这就是我想要的.

但是如果我使用1而不是0

But if I use 1 instead of 0

for mid, group in itertools.groupby(self.data, key=operator.itemgetter(1)):

按元组中的第二个数字分组,我只会得到:

to group by the second number in the tuples, I only get:

[(1, 1, 5.0)]

即使还有其他在该1(第二个)位置具有"1"的元组.

even though there are other tuples that have "1" in that 1 (2nd) position.

推荐答案

itertools. groupby 使用相同的密钥将连续项收集在一起. 如果希望所有项目都使用相同的键,则必须首先对self.data进行排序.

itertools.groupby collects together contiguous items with the same key. If you want all items with the same key, you have to sort self.data first.

for mid, group in itertools.groupby(
    sorted(self.data,key=operator.itemgetter(1)), key=operator.itemgetter(1)):

这篇关于itertools.groupby()无法正确分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆