简体   繁体   English

如何根据 Python3 中的另一个列表对列表中的元素进行分组?

[英]How to group elements in a list in with respect to another list in Python3?

I have 2 lists我有 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']

I want to group the second list based on the same elements in the first list ie我想根据第一个列表中的相同元素对第二个列表进行分组,即

Output has to be Output 必须是

out=[['a','b','c'],['d','e'],['f'],['g','h','i'],['j','k']]

Explanation: the first 3 elements of the first list are the same, so I want the first 3 elements of the 2nd list to be grouped together (and so on)说明:第一个列表的前 3 个元素相同,所以我希望将第二个列表的前 3 个元素组合在一起(依此类推)

If anyone can help out, it would be great!如果有人可以帮忙,那就太好了!

~Thanks ~谢谢

Just zip the lists, then itertools to the rescue.只有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']]

Non- itertools solution: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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM