![](/img/trans.png)
[英]How to conditionally append tuples from one list to another list of tuples?
[英]Fast algorithm needed for finding tuples from within one list inside tuples of another list. Sets?
我有以下列表:
list_1 = [(0, 1, 7, 6), (1, 2, 8, 7), (2, 3, 9, 8), ...]
list_2 = [(0,1), (1,7), (7,8), (3,9), ...]
兩個列表的長度都為 200000 或更多元素。
我需要一個快速算法來檢查list_2
的元素在list_1
的元素中出現的list_2
。 在上面的示例中, list_2
的第二個元素(1,7)
在list_1
出現了兩次,分別出現在第一個和第二個列表元素中。
在我的情況下,如果兩個數字都是list_1
的子集,而與它們的順序無關,那么它就是一個有效的命中。 所以我想我會使用集合並使用.issubset
。
for item1 in list_1:
count = 0
for item2 in list_2:
if set(item2).issubset(set(item1)):
count += count
if count == 1:
do this
if count == 2:
do that
列表中的數據以我預先知道的方式構建,變量count
只能具有值1
或2
。 而且我知道 O(N**2) 的循環根本不智能,並且其中的if
語句不會提高性能。 實際上,在我當前的實現中, list_2
的元素已經是set
類型,但上面的代碼片段更短且易於閱讀。
我相信有針對此任務的智能解決方案。
我的應用程序使用 numpy 和 scipy,因此任何 KD 樹搜索或類似(如果適用)也可以。
編輯
我需要更具體:
list_2
總是包含對。 list_1
每個列表元素可以有 3 個或更多項。do this
do that
我需要跟蹤相應的元素及其關聯,例如通過使用字典。您可以首先進行一些預處理並構建一個以list_1中出現的各個數字為鍵的字典,提供每個鍵作為值list_1中具有該鍵的元組集。
然后從list_2 中找到一對的出現就像獲取在兩個鍵處找到的集合的交集一樣簡單,並獲取結果集的大小。
list_1 = [(0, 1, 7, 6), (1, 2, 8, 7), (2, 3, 9, 8)]
list_2 = [(0,1), (1,7), (7,8), (3,9)]
# per number as dictionary key, list the tuples from list_1 that contain it
d = dict()
for lst in list_1:
for v in lst:
if not v in d: d[v] = set()
d[v].add(lst)
# for each pair, take the intersection of the corresponding lists in d
result = [(lst, len(d[lst[0]].intersection(d[lst[1]]))) for lst in list_2]
print(result)
如果您需要對list_1 中找到的元組進行實際操作,那么您將首先收集這些元組而不取其編號(因此d[lst[0]].intersection(d[lst[1]])
),然后執行您的操作根據len()
提供的內容(1 或 2)對它們進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.