简体   繁体   English

如何根据另一个列表中的连续元素对一个列表中的项目进行分组?

[英]How to group items in one list based on consecutive elements in another list?

I have a simple Data sorting problem:我有一个简单的数据排序问题:

I have two lists:我有两个列表:

List1: [1,1,1,2,3,3,4,5,5] List2: [objectA, objectB, objectC, objectD, ... objectI]列表 1: [1,1,1,2,3,3,4,5,5]列表 2: [objectA, objectB, objectC, objectD, ... objectI]

The lists have the same length.列表具有相同的长度。 I'd like to sort List2 into a nested List as follows:我想将 List2 排序为嵌套列表,如下所示:

List3: [[objectA, objectB, objectC], [objectD], ...]列表 3: [[objectA, objectB, objectC], [objectD], ...]

So basically sort list2 to into sublists according to list1.所以基本上根据 list1 将 list2 排序为子列表。 Is this a list or a dictionary problem and how do I solve it?这是列表问题还是字典问题,我该如何解决?

I think that the best way to solve it is using a dictionary for grouping the elements of List2 according to the elements in List1我认为解决它的最好方法是使用字典根据List1中的元素对List2的元素进行分组

For your example that should be like this对于你的例子应该是这样的

List1 = [1,1,1,2,3,3,4,5,5]
List2 = ['objectA', 'objectB', 'objectC', 'objectD', ... 'objectI']

grouping = {}

for key, value in zip(List1, List2):
  if key not in grouping:
    grouping[key] = []
  grouping[key].append(value)

List3 = [grouping[key] for key in sorted(grouping.keys())]

print(List3)

You can use something like that:你可以使用类似的东西:

from collections import Counter

list1=[1,1,1,2,2,3,4]
list2=["objectA", "objectB", "objectC", "objectD","objectE","objectF","objectG"]
to_dict=dict(Counter(list1).items()) #{1: 3, 2: 2, 3: 1, 4: 1}

final=[]
i=0
for k,v in to_dict.items():
    final.append(list2[i:v+i])
    i+=v

Output(final) :输出(最终)

[
     ['objectA', 'objectB', 'objectC'],
     ['objectD', 'objectE'],
     ['objectF'],
     ['objectG']
]

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

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