使用itertools将连续元组按第二个值分组 [英] Using itertools to group consecutive tuples by second value

查看:46
本文介绍了使用itertools将连续元组按第二个值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组数据,格式为:

I have a set of data in the form:

X1 = [(1,1),(3,1),(5,0),(3,0),(2,1)]

我不知道如何将它们分组,这样:

I can't figure out how to group them such that:

X2 = [[(1,1),(3,1)],[(5,0),(3,0)],[(2,1)]]

即它们按照每个元组中的第二个值以连续方式分组.

i.e. they are grouped in a consecutive fashion by the second value in each tuple.

我知道是这样的:

http://docs.python.org/2/library/itertools.html#itertools.groupby

推荐答案

from itertools import groupby
from operator import itemgetter
X2 = [list(group) for key, group in groupby(X1, itemgetter(1))]

key函数传递给groupby,以获取每个元组的第二个项目,因此groupby将元组按其第二个项目进行分组.

Pass a key function to groupby that fetches the second item of each tuple, so groupby groups the tuples by their second items.

这篇关于使用itertools将连续元组按第二个值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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