2013-10-04 27 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