如何使用if语句和for循环来运行它?

2024-04-19 17:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过使用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

Tags: in程序列表for参数ifrange语句
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

我想我知道你在找什么。如果是这样的话,它就相当笨拙了;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

相关问题 更多 >