2 回答
TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
老實(shí)說-我并不真正了解您的代碼及其背后的想法,因此無法告訴您為什么結(jié)果僅包含所需元組的子集。
但是,我有一個(gè)不同的方法,你可能會(huì)覺得有趣。
主要思想是有一個(gè)可以測(cè)試兩個(gè)元組是否重疊的函數(shù)。此函數(shù)適用于overlap_list. 如果兩個(gè)重疊,則將它們添加到結(jié)果列表中,該列表隨后將包含重復(fù)項(xiàng),因此list(set(result))最終應(yīng)用。但是,您可以將演員表放在列表中,因?yàn)橐唤M都可以,因此我可以...
測(cè)試函數(shù)的想法是簡(jiǎn)單地對(duì)要測(cè)試的兩個(gè)元組的 4 個(gè)值進(jìn)行排序并查看排序順序(請(qǐng)參閱 參考資料numpy.argsort)。如果前兩個(gè)索引是 0/1 或 2/3,則兩個(gè)元組不重疊。
換句話說:針對(duì)存在進(jìn)行測(cè)試,>1它們必須是不相等的,即不能同時(shí)為真或假:
def overlap_test(tpl1, tpl2):
import numpy as np
a, b = np.argsort(tpl1 + tpl2)[:2] > 1
return a != b
這是使用該函數(shù)的循環(huán):
import itertools as it
result = []
for test_tpl, sec_tpl in list(it.combinations(overlap_list, 2)):
if overlap_test(test_tpl, sec_tpl):
result.extend([test_tpl, sec_tpl])
result = list(set(result))
# [(10001657, 10001718),
# (10031556, 10031656),
# (10031548, 10031643),
# (10001657, 10001716),
# (10001656, 10001717)]
我仍然想知道循環(huán)是否不能更有效,并且這樣是否也set無法優(yōu)化對(duì)循環(huán)的需求 - 好吧,也許你會(huì)找到一個(gè)更好的循環(huán)。
編輯:
到目前為止并沒有真正發(fā)現(xiàn)有什么不同,但有一點(diǎn)改進(jìn):
相同的方法,但從set一開始就使用:
def find_overlap_tuples_0(tpl_list):
result = set()
for test_tpl, sec_tpl in list(it.combinations(tpl_list, 2)):
if overlap_test(test_tpl, sec_tpl):
result.add(test_tpl)
result.add(sec_tpl)
return list(result)
# %timeit find_overlap_tuples_0(overlap_list)
# 178 μs ± 4.87 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
有點(diǎn)不同,僅基于排列和分組(似乎稍微快一點(diǎn)):
def find_overlap_tuples_1(tpl_list):
result = set()
no_ovl = set()
for a, grp in it.groupby(it.permutations(tpl_list, 2), lambda x: x[0]):
for b in grp:
if (a not in result) and (b[1] not in no_ovl):
if overlap_test(*b):
result.add(b[0])
result.add(b[1])
break
no_ovl.add(b[0])
return list(result)
# %timeit find_overlap_tuples_1(overlap_list)
# 139 μs ± 1.59 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
似乎您可以對(duì)列表進(jìn)行排序,以便任何重疊的開始和停止都是相鄰的,然后只比較鄰居以確定是否由于不重疊而需要過濾掉任何元組(不需要在代碼末尾進(jìn)行排序,只是更容易在打印輸出中看到重疊的鄰居)。
l = [(10001656, 10001717), (700, 60000), (10001657, 10001718), (10001657, 10001716), (10031548, 10031643), (10031556, 10031656)]
l.sort()
overlap = set()
for a, b in zip(l, l[1:]):
if a[1] >= b[0] and a[1] <= b[1]:
overlap.add(a)
if b[0] >= a[0] and b[0] <= a[1]:
overlap.add(b)
overlap = sorted(overlap)
print(overlap)
# [(10001657, 10001716), (10001657, 10001718), (10031548, 10031643), (10031556, 10031656)]
添加回答
舉報(bào)
