[英]split a list of sublist based on their first elements
if i have a list that looks something like (list a)如果我有一个类似于 (list a) 的列表
my_list=[[3, 1], [3, 0], [3, 0], [3, 1], [4, 1], [4, 0]]
i want to split that list into something like this (list b)我想将该列表拆分为这样的内容(列表 b)
my_list = [ [[3, 1], [3, 0], [3, 0], [3, 1]] , [[4, 1], [4, 0]] ]
as you can see, list b is sorted and grouped together by the values of the first element of the sublists.如您所见,列表 b 按子列表的第一个元素的值进行排序和分组。 The order of the pairs doesn't change.对的顺序不会改变。
thank you!谢谢你!
You can use itertools.groupby
to group on the first element:您可以使用itertools.groupby
对第一个元素进行分组:
my_list = itertools.groupby(my_list, key = lambda e: e[0])
This will give you an itertools.groupby
generator object of (key, list) pairs.这将为您提供 (key, list) 对的itertools.groupby
生成器对象。 Ignore the keys and convert it into a list by doing忽略键并将其转换为列表
[list(e[1]) for e in my_list]
This gives:这给出:
[[[3, 1], [3, 0], [3, 0], [3, 1]], [[4, 1], [4, 0]]]
itertools.groupby(...)
should do the trick: 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]))
Output:输出:
[[[3, 1], [3, 0], [3, 0], [3, 1]], [[4, 1], [4, 0]]]
Ref: https://docs.python.org/2/library/itertools.html#itertools.groupby参考: https : //docs.python.org/2/library/itertools.html#itertools.groupby
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]]] [[[3, 1], [3, 0], [3, 0], [3, 1]], [[4, 1], [4, 0]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.