簡體   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