-2

我试图通过使用 if 语句、for 循环和列表来运行它。该列表是参数的一部分。我不确定如何编写 if 语句并让程序遍历所有不同的单词并设置所有内容。

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
4

2 回答 2

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
于 2013-10-04T23:17:53.860 回答
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
于 2013-10-04T23:30:46.713 回答