Home > Mobile >  How to group items in one list based on consecutive elements in another list?
How to group items in one list based on consecutive elements in another list?

Time:12-17

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?

CodePudding user response:

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)

CodePudding user response:

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