2016-07-14 54 views
3

我有一個代碼樣式問題,我正在尋找我在下面寫的pythonic實現。最後一次迭代後關閉範圍的Pythonic方式

我發佈的(簡化)代碼迭代了一個序列並返回範圍。每個範圍以特定條件開始和結束。範圍不能重疊。我使用變量active來跟蹤是否已經找到範圍的開始。如果在序列結束時有效範圍尚未關閉,則應添加(有input_length作爲結束索引)

下面的代碼按預期工作,但我不喜歡這樣一個事實,即我必須編寫代碼將範圍追加到結果列表兩次。在我遇到的實際問題中,這個塊更長,我不想在for循環之後再次寫它。

你有什麼建議可以改善嗎?

謝謝!

input_length = 100 
results = [] 

active = False 
start = None 
for i in range(input_length): 
    condition = i % 9 == 0 
    if not active and condition: 
     active = True 
     start = i 

    condition2 = i % 13 == 0 
    if active and condition2: 
     active = False 
     # do some additional calculations... 
     results.append((start, i)) 

if active: 
    # do some additional calculations... 
    results.append((start, input_length)) 

print(active) 
print(results) 
+4

需要審查/改進的工作代碼更適合[codereview](http://codereview.stackexchange.com/)。 – syntonym

回答

1

到它的簡單方法是編輯內部條件:

condition2 = i % 13 == 0 
    if active and (condition2 or i == input_length-1)) 
     active = False 
     # do some additional calculations... 
     results.append((start, i if condition2 else i + 1)) 

和去除外層。

如果你想避免i if condition2 else i + 1也許你可以迭代range(input_length + 1)? (這取決於你在迴路中做什麼其他的事情)

+1

您有一個錯誤的錯誤。你需要比較'i == input_length-1',但是你不能只執行'results.append((start,i))'。 –

+0

@Rawing你是對的,我解決了這個問題,雖然我不確定這是否是他現在的一個很好的解決方案。 –

+0

嗯這個解決方案的問題是一個序列,最後一個元素滿足條件,一個不會導致相同的範圍。 – Felix

0

我找到了一個很好的方式,如何做到這一點:

import itertools as it 

il = 100 
results = [] 
def fun1(): 
    active = False 
    start = None 
    for i in range(il): 
     condition = i % 9 == 0 
     if not active and condition: 
      active = True 
      start = i 
     condition2 = i % 13 == 0 
     if active and condition2: 
      active = False 
      # do some additional calculations... 
      results.append((start, i)) 
    if active: 
     # do some additional calculations... 
     results.append((start, il)) 
    return results 

def fun2(): 
    a=b=0 
    while b<il: 
     yield (a,b) 
     b=b+13 
     a=a+9 
     while a<=b-13: 
      a=a+9 
    if a<il: 
     yield (a,il) 

print fun1() 
print 
print [(a,b) for (a,b) in fun2()] 

請檢查金正日的不同值的代碼和之前比較它的功能你用吧。