根据第一个元素拆分子列表列表

split a list of sublist based on their first elements

如果我有一个类似于(列表 a)的列表

my_list=[[3, 1], [3, 0], [3, 0], [3, 1], [4, 1], [4, 0]]

我想将该列表拆分成这样的内容(列表 b)

my_list = [ [[3, 1], [3, 0], [3, 0], [3, 1]] , [[4, 1], [4, 0]] ]

如您所见,列表 b 按子列表第一个元素的值排序和分组在一起。对的顺序不变。

谢谢!

itertools.groupby(...) 应该可以解决问题:

import itertools

my_list=[[3, 1], [3, 0], [3, 0], [3, 1], [4, 1], [4, 0]]
#although your input seems to be sorted by 1st element I'll put it in here, in case if it wouldn't be
my_list=sorted(my_list, key=lambda x: x[0])

my_list=list(list(el) for k, el in itertools.groupby(my_list, key=lambda x: x[0]))

输出:

[[[3, 1], [3, 0], [3, 0], [3, 1]], [[4, 1], [4, 0]]]

参考:https://docs.python.org/2/library/itertools.html#itertools.groupby

您可以使用 itertools.groupby 对第一个元素进行分组:

my_list = itertools.groupby(my_list, key = lambda e: e[0])

这将为您提供一个 itertools.groupby (key, list) 对的生成器对象。忽略键并通过

将其转换为列表
[list(e[1]) for e in my_list]

这给出:

[[[3, 1], [3, 0], [3, 0], [3, 1]], [[4, 1], [4, 0]]]
my_list=[[3, 1], [3, 0], [3, 0], [3, 1], [4, 1], [4, 0]]
new_list =[]

j =0
for i in list(set([ value[0] for value in my_list])) :
    temp_list = []
    while (j < len(my_list)) and (my_list[j][0] == i):
        temp_list.append(my_list[j])
        j=j+1
    new_list.append(temp_list)


print (new_list)

[[[3, 1], [3, 0], [3, 0], [3, 1]], [[4, 1], [4, 0]]]