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

2024-05-26 04:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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']]

我想根据每个列表的前2个条目来减少列表,以获得

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

有没有一种方法可以在不创建虚拟列表的情况下高效地执行此操作?你知道吗


Tags: 方法child列表is情况条目malefemale
2条回答

对于这样的任务,你可以使用字典:

>>> li=[['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']]
>>> 
>>> d={}
>>> 
>>> for i,j,k in li:
...   d.setdefault((i,j),[]).append(k)
... 
>>> d
{('boy', '121'): ['is a male child', 'is male', 'is a child'], ('girl', '122'): ['is a female child', 'is a child']}

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

如果您想让元素在一个容器中,您可以在项目上循环,并将值转换为tuple,然后用key:

>>> [i+tuple(j) for i,j in d.items()]
[('boy', '121', 'is a male child', 'is male', 'is a child'), ('girl', '122', 'is a female child', 'is a child')]

正如@jornsharpe所说,作为一种更优雅的方式,您还可以使用collections.defaultdict

>>> from collections import defaultdict
>>> 
>>> d=defaultdict(list)
>>> for i,j,k in li:
...   d[i,j].append(k)
... 
>>> d
defaultdict(<type 'list'>, {('boy', '121'): ['is a male child', 'is male', 'is a child'], ('girl', '122'): ['is a female child', 'is a child']})

您可以使用^{}来实现:

>>> 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])

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element.

相关问题 更多 >