繁体   English   中英

检查值或值列表是否是python中列表子集的最快方法

[英]Fastest way to check if a value or list of values is a subset of a list in python

我有一个非常大的列表,称为main_list ,包含大约 1300 万个列表,每个列表包含 6 个数字。 我正在寻找一种方法来过滤掉不包含某些值的任何列表。 例如,要创建仅包含值为 4 和 5 的列表的新列表列表,我的代码按如下方式工作:

and_include = []
temp_list=[4,5]
for sett in main_list:
    if set(temp_list).issubset(sett):
        and_include.append(sett)

这大约需要 5 秒才能运行,这对于频繁使用来说可能很烦人,所以我想知道是否有更快的方法来做到这一点,使用 numpy 或 cython?

我对 cython 不是很熟悉,但我尝试以这种方式实现,编译它,但我得到了一个错误。

def andinclude(list main_list,list temp_list):
    and_include=[]
    for sett in main_list:
        if set(temp_list).issubset(sett):
            and_include.append(sett)
    return and_include

希望有更快的方法?

这是一个numpy解决方案:

import numpy as np

# Randomly generate 2d array of integers
np.random.seed(1)
a = np.random.randint(low=0, high=9, size=(13000000, 6))

# Use numpy indexing to filter rows
results = a[(a == 4).any(axis=1) & (a == 5).any(axis=1)]

结果:

In [35]: print(results.shape)
(3053198, 6)

In [36]: print(results[:5])
[[5 5 4 5 5 1]
 [5 5 4 3 8 6]
 [2 5 8 1 1 4]
 [0 5 4 1 1 5]
 [3 2 5 2 4 6]]

定时:

In [37]: %timeit results = a[(a == 4).any(axis=1) & (a == 5).any(axis=1)]
923 ms ± 38.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

如果您需要将结果转换回列表列表而不是 2d numpy 数组,您可以使用:

l = results.tolist()

这增加了大约 50% 的时间在我的机器上运行,但仍然比任何涉及循环 Python 列表的解决方案都要快。

您可以使用列表理解而不是在循环中附加。 此外,您可能希望将set(temp_list)的结果存储在局部变量中,这样就不会为相同的结果调用set 1300 万次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM