如何使用python将几个列表折叠成一个列表?

如何使用python将几个列表折叠成一个列表?,python,Python,例如,我有一个列表,看起来像这样 # [ # [elem1, ... comment11] # [elem1, ... comment12] # ... # [elem2, ... comment21] # ... # ] 我应该从中得出类似的结论: # [ # [elem1, ... [comment11, comment12]] # [elem2, ... [comment21, ...]] # ... # ] 与列表中的元素(仅每个列表的最后一个元素)不同的是,这些元素将连接到一个新列

例如,我有一个列表,看起来像这样

# [
# [elem1, ... comment11]
# [elem1, ... comment12]
# ...
# [elem2, ... comment21]
# ...
# ]
我应该从中得出类似的结论:

# [
# [elem1, ... [comment11, comment12]]
# [elem2, ... [comment21, ...]]
# ...
# ]

与列表中的元素(仅每个列表的最后一个元素)不同的是,这些元素将连接到一个新列表。

您正在查找的是
defaultdict
。从:

为了适应您的问题,代码可能如下所示:

>>> s = [['elem1', 'comment11'],['elem1', 'comment12'],['elem2', 'comment21']]
>>> d = defaultdict(list)
>>> for l in s:
        d[l[0]].append(*l[1:])
>>> d.items()
[('elem2', ['comment21']), ('elem1', ['comment11', 'comment12'])]
使用:


但根据他的问题,他似乎还有其他一些项目在名单上。那么这个代码有多有效?
operator.itemgetter(0)
lambda x:x[0]
更有效(可以说更具表现力)根据@FrerichRaabe,我更新了答案,使用
operator.itemgetter
。谢谢您的评论。@SravanKGhantasala,我更新了代码以处理列表中的其他项目。谢谢你的评论。所以,这两种变体都是我的决定。我选了这个。泰铢:)OP有一个列表列表,而不是元组列表,因此您需要类似于
((x[0],x[-1])的输入列表中的x)
来生成元组。@FrerichRaabe我处理过您的评论吗?(仍在学习Python)看起来更好,但我认为您希望使用
l[-1]
(即最后一个列表元素)而不是
l[1://code>,因为OP编写了“(每个列表中只有最后一个元素)将被连接到一个新列表”。我假设
指的是列表中包含多个元素的可能性(尽管示例没有显示它处理这种可能性。
>>> s = [['elem1', 'comment11'],['elem1', 'comment12'],['elem2', 'comment21']]
>>> d = defaultdict(list)
>>> for l in s:
        d[l[0]].append(*l[1:])
>>> d.items()
[('elem2', ['comment21']), ('elem1', ['comment11', 'comment12'])]
>>> import itertools
>>> import operator
>>> a_list = [
...     ['elem1', 'other_item1', 'other_item1', 'comment11'],
...     ['elem1', 'other_item2', 'other_item2', 'comment12'],
...     ['elem2', 'other_item3', 'other_item3', 'comment21'],
... ]
>>> new_list = []
>>> for _, grp in itertools.groupby(a_list, key=operator.itemgetter(0)):
...     grp = list(grp)
...     new_list.append(grp[0][:-1] + [[item[-1] for item in grp]])
... 
>>> new_list
[['elem1', 'other_item1', 'other_item1', ['comment11', 'comment12']],
 ['elem2', 'other_item3', 'other_item3', ['comment21']]]