如果条目匹配,则减少列表列表

时间:2015-04-29 10:55:35

标签: python list set

我在python中有一个类似

的列表
[['boy','121','is a male child'],['boy','121','is male'],['boy','121','is a child'],['girl','122','is a female child'],['girl','122','is a child']]

我想根据每个列表中的前两个条目减少列表,以获取

[['boy','121',is a male child, is male, is a child'],['girl','122','is a female child','is a child']]

有没有办法在不创建虚拟列表的情况下有效地完成这项工作?

1 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupby

>>> l = [['boy','121','is a male child'],['boy','121','is male'],['boy','121','is a child'],['girl','122','is a female child'],['girl','122','is a child']]
>>> import itertools
>>> [k+[m[2] for m in v] for k,v in itertools.groupby(l,key = lambda x:x[:2])]
[['boy', '121', 'is a male child', 'is male', 'is a child'], ['girl', '122', 'is a female child', 'is a child']]

来自文档

itertools.groupby(iterable[, key])
     

创建一个迭代器,从迭代中返回连续的键和组。关键是计算每个键值的函数   元件。