在Python中按长度拆分列表

2024-04-25 12:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑到以下问题,在Python中最有效(或合理有效)的方法是什么:

问题。给定一个列表

L = [list_0, list_1, list_2, list_3, ..., list_n]

其中len(listïi)<;=3,假设,对于L中的每个列表,我们如何将L拆分为Lï1、Lï2、Lï3,其中Lï1只有长度1的列表,Lï2只有长度2的列表,Lï3只有长度3的列表?你知道吗

可能的解决方案。这里是我能做的最好的;我还包括了一个样本集。它在我的电脑上运行大约8.6秒

import time

# These 4 lines make a large sample list-of-list to test on.
asc_sample0 = [[i] for i in range(500)]
asc_sample1 = [[i,j] for i in range(500) for j in range(20)]
asc_sample2 = [[i,j,k] for i in range(20) for j in range(10) for k in range(20)]
asc_sample = asc_sample0 + asc_sample1 + asc_sample2

start = time.clock()
cells0 = [i for i in asc if len(i) == 1]
cells1 = [i for i in asc if len(i) == 2]
cells2 = [i for i in asc if len(i) == 3]
print time.clock() - start

我还尝试“弹出”元素并将其附加到列表cells0等,但这花费了相当长的时间。我还尝试附加然后删除那个元素,这样我就可以在一个循环中完成,比如说,有10^10个大小为1的列表,但是只有一些大小为2和3的列表,这样做很好,但是,总的来说,效率不高。你知道吗

我很欣赏一些好主意。我知道其中一个答案很可能是“用C编写”,但现在我只想看看Python解决方案。你知道吗


Tags: samplein列表forleniftimerange
3条回答

一个老式的解决方案在这里可能更有效:

cells0, cells1, cells2 = [], [], []

for lst in asc_sample:
    n = len(lst)
    if n == 1:
        cells0.append(lst)
    elif n == 2:
        cells1.append(lst)
    else:
        cells2.append(lst)

这绝对是最好的,因为它并行运行。不过,您应该了解的另一件事是itertools.groupby和内置的filter方法。你知道吗

result = dict()

for lst in L:
    result.setdefault(len(lst), []).append(lst)

print result

输出

{
 1: [[0], [1], [2], [3]],
 2: [[0, 0], [0, 1], [0, 2]],
 3: [[0, 0, 0], [0, 0, 1], [0, 0, 2]]
}

相关问题 更多 >