简体   繁体   中英

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]

The lists have the same length. I'd like to sort List2 into a nested List as follows:

List3: [[objectA, objectB, objectC], [objectD], ...]

So basically sort list2 to into sublists according to list1. 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

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']
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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