我需要一个函数或代码来连接列表中的某些列表。我在这个网站搜索了一个解决方案,但是我找不到合适的解决方案,我尝试了很多没有结果的解决方案。
我的代码中有这个例子:
列表是:
[['He', 'is', [0, 1, 2, 3, 4, 5, 6, 7]],
['is', 'angry.', [0, 1]],
['is', 'happy.', [2, 3]],
['is', 'sleep.', [4]],
['angry.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['happy.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['going.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sleep.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sad.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]]]
我需要对具有相同第一个值的列表进行分组,例如通过'是',输出应该是:
[['He', 'is', [0, 1, 2, 3, 4, 5, 6, 7]],
['is', ['angry.',' happy.', 'sleep.'], [[0, 1], [2, 3], [4]]],
['angry.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['happy.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['going.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sleep.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sad.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]]]
有什么建议吗?
答案 0 :(得分:0)
您可以尝试使用itertools.groupby
将列表与内部列表的第一个值分组,然后压缩组数据并合并它们,如下所示:
from itertools import groupby
from operator import itemgetter
source = [['He', 'is', [0, 1, 2, 3, 4, 5, 6, 7]],
['is', 'angry.', [0, 1]],
['is', 'happy.', [2, 3]],
['is', 'sleep.', [4]],
['angry.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['happy.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['going.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sleep.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sad.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]]]
groups = groupby(source, itemgetter(0))
result = []
for key,data in groups:
list_data = list(data)
if len(list_data) == 1:
result.append(list_data[0])
elif len(list_data) >1:
zip_data = zip(*list_data) # list(zip(*list_data)) for python 3
result.append([key]+[list(zip_data[1])]+[list(zip_data[2])])
result
将是:
[['He', 'is', [0, 1, 2, 3, 4, 5, 6, 7]],
['is', ['angry.', 'happy.', 'sleep.'], [[0, 1], [2, 3], [4]]],
['angry.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['happy.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['going.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sleep.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]],
['sad.', 'He', [0, 1, 2, 3, 4, 5, 6, 7]]]