我想通過瀏覽 catch_list_7=[100,7] 來檢查元素的總和是否在 df=[200,107,25,30] 中,但是當我輸入 200(比總和更大的值)時,我的回圈保持不變在 200 并且不繼續。當我洗掉 200 值時,它起作用了。
is_match =False
for i in catch_list_7 :
if is_match ==False:
for d in df:
if abs(d-(i[0] i[1]))<=0.2:
catch_list.append([i[0] i[1],i[0],i[1]])
print("Total Gross", catch_list)
is_match = True
break
else:
break
uj5u.com熱心網友回復:
我建議將您的代碼封裝到函式中;每個做一件精確事情的邏輯塊都應該是一個功能。
這將使每個人都更容易理解您的代碼。“每個人”的意思是:閱讀您問題的 StackOverflow 用戶;你的同事;更重要的是,你現在的自己;一個月后,當您以全新的眼光審視自己的代碼時,您就會發現自己。
因此,創建一個接受值串列和目標總和串列的小函式,并檢查兩個值是否與目標相加:
from itertools import combinations
def catch_pairs_that_add_to_target(values, targets):
targets_set = set(targets)
caught_pairs = []
for x,y in combinations(values, 2):
if x y in targets_set:
caught_pairs.append((x,y))
return caught_pairs
# TESTING
print( catch_pairs_that_add_to_target([100, 42, 7, 158], [200, 107, 25, 30]) )
# [(100, 7), (42, 158)]
如果我們正在處理浮點數,我們不應該測驗是否完全相等;有math.isclose這種情況:
from itertools import combinations
from math import isclose
def catch_pairs_that_add_to_target(values, targets):
caught_pairs = []
for x,y in combinations(values, 2):
if any(isclose(x y, z, abs_tol=0.2) for z in targets):
caught_pairs.append((x,y))
return caught_pairs
# TESTING
print( catch_pairs_that_add_to_target([100.1, 42.05, 7.07, 158.1], [200.0, 107.0, 25.0, 30.0]) )
# [(100.1, 7.07), (42.05, 158.1)]
相關檔案:
- itertools.combinations迭代所有值對;
- set因為
x y in targets如果targets是一個集合比如果它是一個串列要快得多; - math.isclose測驗浮點數的近似相等性;
- any檢查是否至少有一個元素滿足謂詞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376766.html
