如何根据 Python3 中的另一个列表对列表中的元素进行分组?
How to group elements in a list in with respect to another list in Python3?
我有 2 个列表
in1=[1,1,1,2,2,3,4,4,4,5,5]
in2=['a','b','c','d','e','f','g','h','i','j','k']
我想根据第一个列表中的相同元素对第二个列表进行分组,即
输出必须是
out=[['a','b','c'],['d','e'],['f'],['g','h','i'],['j','k']]
说明:第一个列表的前 3 个元素相同,所以我想将第二个列表的前 3 个元素组合在一起(依此类推)
如果有人能帮忙,那就太好了!
~谢谢
只是 zip
列表,然后 itertools
来救援。
from itertools import groupby
in1 = [1,1,1,2,2,3,4,4,4,5,5]
in2 = ['a','b','c','d','e','f','g','h','i','j','k']
result = [[c for _, c in g] for _, g in groupby(zip(in1, in2), key=lambda x: x[0])]
print(result)
# [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i'], ['j', 'k']]
非itertools
解决方案:
in1 = [1,1,1,2,2,3,4,4,4,5,5]
in2 = ['a','b','c','d','e','f','g','h','i','j','k']
result = [[]]
key = in1[0]
for k, v in zip(in1, in2):
if k != key:
result.append([])
key = k
result[-1].append(v)
print(result)
# [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i'], ['j', 'k']]
我有 2 个列表
in1=[1,1,1,2,2,3,4,4,4,5,5]
in2=['a','b','c','d','e','f','g','h','i','j','k']
我想根据第一个列表中的相同元素对第二个列表进行分组,即
输出必须是
out=[['a','b','c'],['d','e'],['f'],['g','h','i'],['j','k']]
说明:第一个列表的前 3 个元素相同,所以我想将第二个列表的前 3 个元素组合在一起(依此类推)
如果有人能帮忙,那就太好了!
~谢谢
只是 zip
列表,然后 itertools
来救援。
from itertools import groupby
in1 = [1,1,1,2,2,3,4,4,4,5,5]
in2 = ['a','b','c','d','e','f','g','h','i','j','k']
result = [[c for _, c in g] for _, g in groupby(zip(in1, in2), key=lambda x: x[0])]
print(result)
# [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i'], ['j', 'k']]
非itertools
解决方案:
in1 = [1,1,1,2,2,3,4,4,4,5,5]
in2 = ['a','b','c','d','e','f','g','h','i','j','k']
result = [[]]
key = in1[0]
for k, v in zip(in1, in2):
if k != key:
result.append([])
key = k
result[-1].append(v)
print(result)
# [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i'], ['j', 'k']]