【问题标题】:Fastest way to split a list into a list of lists based on another list of lists根据另一个列表列表将列表拆分为列表列表的最快方法
【发布时间】:2021-05-23 10:21:57
【问题描述】:

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

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

我还有一个list的list,是把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]]

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

【问题讨论】:

  • 这里的常数因子是什么?您是否需要基于同一个 partitions 为多个 lst 完成这项工作,反之亦然,还是每个任务都使用不同的值?
  • 当然partitions 是常数因子。我不明白描述中如何不清楚。

标签: python list algorithm performance partitioning


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-12-13
      • 2011-01-05
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      相关资源
      最近更新 更多