-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 に答える