2017-06-21 99 views
1

我有以下問題。我有一個參數frc_size。根據fcr_size的大小,必須在if條件中檢查更多的距離。有辦法處理這種智能並縮短所有這些表達式嗎?例如,對於fcr_size = 3,如果條件將是這樣的:Python:多個條件取決於參數

minusscore = 2 

for coords in full_box: 
    mindist = float("inf") 
    for m in range(len(lineSegmentPairs[0])): 
     newdist = dist(lineSegmentPairs[0][m], lineSegmentPairs[1][m], coords) 
     if newdist<mindist: 
      mindist=newdist 
    if mindist <= radius : 
     val1 = int(sparse1.get(coords,"0")[0]) - minusscore 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +1) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 3 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +2) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 2 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +3) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 1 
     sparse1[coords] = [str(val1)] 
    elif mindist > (radius +3) : 
     continue 

但如果fcr_size將是如圖4所示,比一個額外如果條件想是必要的:

minusscore = 2 

for coords in full_box: 
    mindist = float("inf") 
    for m in range(len(lineSegmentPairs[0])): 
     newdist = dist(lineSegmentPairs[0][m], lineSegmentPairs[1][m], coords) 
     if newdist<mindist: 
      mindist=newdist 
    if mindist <= radius : 
     val1 = int(sparse1.get(coords,"0")[0]) - minusscore 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +1) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 4 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +2) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 3 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +3) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 2 
     sparse1[coords] = [str(val1)] 
    elif mindist <= (radius +4) : 
     val1 = int(sparse1.get(coords,"0")[0]) + 1 
     sparse1[coords] = [str(val1)] 
    elif mindist > (radius +4) : 
     continue 
+0

你對'mindist <=(radius +4)'和'mindist <=(radius +3)'的行爲是一樣的,是一個錯字嗎? – LoicM

+1

我建議你使用4個空格而不是8個縮進。它肯定會提高可讀性,請參閱[PEP8](https://www.python.org/dev/peps/pep-0008/#indentation)。 – rodgdor

+0

是的,我編輯它看起來像fcr_size 4 – Varlor

回答

2

也許是這樣的?

if mindist <= radius: 
    val1 = int(sparse1.get(coords,"0")[0]) - minusscore 
    sparse1[coords] = [str(val1)] 
elif mindist > (radius + fcr_size): 
    continue 
else: 
    for i in range(fcr_size): 
    if mindist <= radius + i + 1: 
     val1 = int(sparse1.get(coords,"0")[0]) + (fcr_size - i) 
     sparse1[coords] = [str(val1)] 
     break 
+0

我想你想在'if'語句中使用'radius + i + 1'。 – jack6e

+0

好點。編輯。 – MCBama

+0

但是,我怎麼能包括論證mindist <=半徑,無論如何fcr_size是一個負分數的行動。如果我嘗試使用elif for for循環,它不工作 – Varlor

1

看來,代碼在if語句中遵循一個模式並可以變成for循環。每個elif語句可以是循環的一個迭代,而不是硬編碼的數字。它會顯着減少你的代碼的大小

+0

...並使其更加靈活。 – Alfe