我有子列表
list=[['RD-2','a',120],['RD-2','b',125],['RD-2','c',127],['RD-3','a',120],['RD-3','b',140],['RD-5','a',120]]
我想基于每个子列表的第一个元素在列表中创建单独的子列表。输出应如下所示
finallist=[[['RD-2','a',120],['RD-2','b',125],['RD-2','c',127]],[['RD-3','a',120],['RD-3','b',140]],['RD-5','a',120]]
我尝试使用if条件在forloop中运行,但无法正常工作。 帮帮我
答案 0 :(得分:2)
使用itertools.groupby
例如:
from itertools import groupby
lst=[['RD-2','a',120],['RD-2','b',125],['RD-2','c',127],['RD-3','a',120],['RD-3','b',140],['RD-5','a',120]]
res = [list(v) for i, v in groupby(lst, lambda x: x[0])] #GroupBy first element.
print(res)
输出:
[[['RD-2', 'a', 120], ['RD-2', 'b', 125], ['RD-2', 'c', 127]], [['RD-3', 'a', 120], ['RD-3', 'b', 140]], [['RD-5', 'a', 120]]]
答案 1 :(得分:2)
无需进行编排,您可以使用collections.defaultdict
:
from collections import defaultdict
L = [['RD-2','a',120],['RD-2','b',125],['RD-2','c',127],
['RD-3','a',120],['RD-3','b',140],['RD-5','a',120]]
dd = defaultdict(list)
for key, value1, value2 in L:
dd[key].append([value1, value2])
## Python 3.x, use * unpacking
# for key, *values in L:
# dd[key].append(values)
res = [[[key, value] for value in values] for key, values in dd.items()]
print(res)
# [[['RD-2', ['a', 120]], ['RD-2', ['b', 125]], ['RD-2', ['c', 127]]],
# [['RD-3', ['a', 120]], ['RD-3', ['b', 140]]],
# [['RD-5', ['a', 120]]]]
答案 2 :(得分:0)
如果组始终是连续的,则可以使用groupby,否则,可以根据第一个元素对子列表进行排序,然后进行分组:
from itertools import groupby
from operator import itemgetter
lst=[['RD-2','a',120],['RD-2','b',125],['RD-2','c',127],['RD-3','a',120],['RD-3','b',140],['RD-5','a',120]]
result = [list(v) for _, v in groupby(lst, key=itemgetter(0))]
print(result)
输出
[[['RD-2', 'a', 120], ['RD-2', 'b', 125], ['RD-2', 'c', 127]], [['RD-3', 'a', 120], ['RD-3', 'b', 140]], [['RD-5', 'a', 120]]]