根据另一个列表列表将列表拆分为列表列表的最快方法

Fastest way to split a list into a list of lists based on another list of lists

假设我有一个列表,其中包含 0 到 9 范围内的 5 个唯一整数。

import random
lst = random.sample(range(10), 5)

我还有一个列表列表,是将0到19的整数分成6组得到的:

partitions = [[8, 12], [2, 4, 16, 19], [1, 6, 7, 13, 14, 17], [3, 15, 18], [5, 9, 10, 11], [0]]

现在我想根据参考 partitions 拆分 lst。 例如,如果我有

lst = [0, 1, 6, 8, 9]

我希望输出是这样的列表列表:

res = [[0], [1, 6], [8], [9]]

我希望算法尽可能快。有什么建议吗?

res=[]

for sublist in partitions: # go through all sublists in partitions
    match = [i for i in lst if i in sublist] # find matching numbers in sublist and lst
    if match: # if it is empty don't append it to res
        res.append(match)
# at this point res is [[8], [1, 6], [9], [0]]                                                                                                         
print(sorted(res)) # use sorted to get desired output

我不知道这是否是最快的算法,但它有效

import random
lst = random.sample(range(10), 5)
partitions = [[8, 12], [2, 4, 16, 19], [1, 6, 7, 13, 14, 17], [3, 15, 18], [5, 9, 10, 11], [0]]
sequence = []
result = []

for i in range(5):
    for j in range(len(partitions)):
        if lst[i] in partitions[j]:
            if j in sequence:
                where = sequence.index(j)
                result[where] += [lst[i]]
            else:
                result += [[lst[i]]]
                sequence += [j]
            break
print(result)