在列表列表中循环

Looping within a list of list

我有一个项目列表(每个项目都是一个列表)

[
['a', 'v1', 'b', 'l']
['a', 'v2', 'b', 'm']
['a', 'v2', 'b, 'n']
['a', 'v3', 'b', 'o']
]

我希望输出按元素 (v's) 的第二项分组,同样在一组列表中,这样输出是

[[['a', 'v1', 'b', 'l']][['a', 'v2', 'b', 'm']['a', 'v2', 'b', 'n']][['a','v2','b','o']]]

非常感谢任何回复,我怎样才能在 python 中实现相同的效果。无法获得要应用的 itertools。不确定不应该在这里应用 itertools,如果是的话如何?否则这里还有什么其他选择可以实现。

itertools.groupy() 是正确的工具,但请记住 documentation 说:

Generally, the iterable needs to already be sorted on the same key function.

from itertools import groupby
from operator import itemgetter

data = [
['a', 'v1', 'b', 'l'],
['a', 'v2', 'b', 'm'],
['a', 'v2', 'b', 'n'],
['a', 'v3', 'b', 'o'],
]

data_sorted = sorted(data, key=itemgetter(1))
for key, group in itertools.groupby(data_sorted, key=itemgetter(1)):
    print(list(group))

产出

[['a', 'v1', 'b', 'l']]
[['a', 'v2', 'b', 'm'], ['a', 'v2', 'b', 'n']]
[['a', 'v3', 'b', 'o']]

您可以使用列表表达式将其缩短:

[list(group) for key, group in itertools.groupby(data_sorted, key=itemgetter(1))]

给予

[[['a', 'v1', 'b', 'l']], [['a', 'v2', 'b', 'm'], ['a', 'v2', 'b', 'n']], [['a', 'v3', 'b', 'o']]]