Say I have a list that contains 5 unique integers in the range of 0 to 9.
JavaScript
x
3
1
import random
2
lst = random.sample(range(10), 5)
3
I also have a list of lists, which is obtained by splitting integers from 0 to 19 into 6 groups:
JavaScript
1
2
1
partitions = [[8, 12], [2, 4, 16, 19], [1, 6, 7, 13, 14, 17], [3, 15, 18], [5, 9, 10, 11], [0]]
2
Now I want to split lst
based on the reference partitions
.
For example, if I have
JavaScript
1
2
1
lst = [0, 1, 6, 8, 9]
2
I expect the output to be a list of lists like this:
JavaScript
1
2
1
res = [[0], [1, 6], [8], [9]]
2
I want the algorithm to be as fast as possible. Any suggestions?
Advertisement
Answer
JavaScript
1
9
1
res=[]
2
3
for sublist in partitions: # go through all sublists in partitions
4
match = [i for i in lst if i in sublist] # find matching numbers in sublist and lst
5
if match: # if it is empty don't append it to res
6
res.append(match)
7
# at this point res is [[8], [1, 6], [9], [0]]
8
print(sorted(res)) # use sorted to get desired output
9