Python:如何在列表列表中将类似列表组合在一起?

new*_*bie 2 python group-by list

我在python中有一个列表列表.我想将类似的列表组合在一起.也就是说,如果每个列表的前三个元素相同,那么这三个列表应该放在一个组中.例如

[["a", "b", "c", 1, 2],

["d", "f", "g", 8, 9],

["a", "b", "c", 3, 4],

["d","f", "g", 3, 4],

["a", "b", "c", 5, 6]]
Run Code Online (Sandbox Code Playgroud)

我希望这看起来像

[[["a", "b", "c", 1, 2],

["a", "b", "c", 5, 6],

["a", "b", "c", 3, 4]],

[["d","f", "g", 3, 4],

["d", "f", "g", 8, 9]]]
Run Code Online (Sandbox Code Playgroud)

我可以通过运行迭代器并手动比较两个连续列表中的每个元素然后根据这些列表中相同的元素来执行此操作,我可以决定将它们组合在一起.但我只是想知道是否有任何其他方式或pythonic方式来做到这一点.

Kas*_*mvd 6

你可以使用itertools.groupby:

>>> A=[["a", "b", "c", 1, 2],
...    ["d", "f", "g", 8, 9],
...    ["a", "b", "c", 3, 4],
...    ["d","f", "g", 3, 4],
...    ["a", "b", "c", 5, 6]]
>>> from operator import itemgetter
>>> [list(g) for _,g in groupby(sorted(A),itemgetter(0,1,2)]
[[['a', 'b', 'c', 1, 2], ['a', 'b', 'c', 3, 4], ['a', 'b', 'c', 5, 6]], [['d', 'f', 'g', 3, 4], ['d', 'f', 'g', 8, 9]]] 
Run Code Online (Sandbox Code Playgroud)