2013-10-04 34 views
-2

我想通過使用if語句,for循環和列表來運行它。該列表是參數的一部分。我不知道如何編寫if語句,並讓程序循環遍歷所有不同的單詞,並設置它應該是什麼樣的一切。如何使if語句和for循環運行?

newSndIdx=0; 
    for i in range (8700, 12600+1): 
    sampleValue=getSampleValueAt(sound, i) 
    setSampleValueAt(newSnd, newSndIdx, sampleValue) 
    newSndIdx +=1 

    newSndIdx=newSndIdx+500 
    for i in range (15700, 17600+1): 
    sampleValue=getSampleValueAt(sound, i) 
    setSampleValueAt(newSnd, newSndIdx, sampleValue) 
    newSndIdx +=1 

    newSndIdx=newSndIdx+500  
    for i in range (18750, 22350+1): 
    sampleValue=getSampleValueAt(sound, i) 
    setSampleValueAt(newSnd, newSndIdx, sampleValue) 
    newSndIdx +=1 

    newSndIdx=newSndIdx+500  
    for i in range (23700, 27250+1): 
    sampleValue=getSampleValueAt(sound, i) 
    setSampleValueAt(newSnd, newSndIdx, sampleValue) 
    newSndIdx +=1 

    newSndIdx=newSndIdx+500  
    for i in range (106950, 115300+1): 
    sampleValue=getSampleValueAt(sound, i) 
    setSampleValueAt(newSnd, newSndIdx, sampleValue) 
    newSndIdx+=1 
+1

請稍微具體一點。你的問題是什麼,你對你的程序有什麼期望? – aIKid

+1

這個描述太模糊了。它不是已經運行了嗎?爲什麼你需要使用'if','for loop'和'list'?他們是爲了什麼?這些「不同的詞」是什麼,你需要設置什麼? –

+0

這已經工作,但我想濃縮到一個if語句和一個for循環。 for循環會遍歷所有不同的範圍,並且完成這個程序已經做的事情。 –

回答

2

約(如果不需要)什麼:

ranges = (
    (8700, 12600), 
    (15700, 17600), 
    (18750, 22350), 
    (23700, 27250), 
    (106950, 115300), 
) 

newSndIdx = 0 

for start, end in ranges: 
    for i in range(start, end + 1): 
     sampleValue = getSampleValueAt(sound, i) 
     setSampleValueAt(newSnd, newSndIdx, sampleValue) 
     newSndIdx += 1 
    newSndIdx += 500 
+0

謝謝你這個作品,但它只播放一個單詞(我可以聽到) –

+0

我認爲你想'newSndIdx + = 500',而不是'= 500'。這樣,它就會覆蓋每個新分段的軌道的相同部分,而不是在分段之間留下間隙。 – abarnert

+0

添加「+」完美工作 –

0

我想我知道你在找什麼在這裏。如果是這樣,它很笨拙; GaretJax重新設計它的方式更簡單,更清晰(並且更加高效,可以啓動)。但它是可行的:

# Put the ranges in a list: 
ranges = [ 
    (8700, 12600), 
    (15700, 17600), 
    (18750, 22350), 
    (23700, 27250), 
    (106950, 115300), 
] 

newSndIdx = 0 

# Write a single for loop over the whole range: 
for i in range(number_of_samples): 
    # If the song is in any of the ranges: 
    if any(r[0] <= i <= r[1] for r in ranges): 
     # Do the work that's the same for each range: 
     sampleValue=getSampleValueAt(sound, i) 
     setSampleValueAt(newSnd, newSndIdx, sampleValue) 
     newSndIdx +=1 

但是,這仍然缺少你爲每個範圍添加500的位;要做到這一點,你需要另一個if,如:

if any(r[0] <= i <= r[1] for r in ranges): 
     if any(r[0] == i for r in ranges[1:]): 
      newSndIdx += 500 
     # The other stuff above