在循环中使用Python的Max()函数

0 投票
3 回答
7026 浏览
提问于 2025-04-18 18:50

我正在尝试写一个程序,用来找出声音样本中的最大值。这个循环会返回所有样本的值,但我不知道怎么才能打印出最大的那个值。

def largest():
f=pickAFile()
sound=makeSound(f)
for i in range(1,getLength(sound)):
  value=getSampleValueAt(sound,i)
print max([value])

3 个回答

0

我没有测试过,但可能是这样:

def largest():
 f=pickAFile()
 sound=makeSound(f)
 value = [ getSampleValueAt(sound,i) for i in range(1,getLength(sound)) ]
 print max(value)
1

别忘了我们在处理的是音频数据,可能有数百万个样本。如果你想在空间和时间上都保持高效,那么你得依赖那些看起来不那么吸引人的方法:

def largest():
    f = pickAFile()
    sound = makeSound(f)
    max = getSampleValueAt(sound, 1) # FIX ME: exception (?) if no data
    idx = 2
    while idx < getLength(sound):
        v = getSampleValueAt(sound, i)
        if v > max:
            max = v
        i += 1

    print max

基于生成器的解决方案在空间上也很高效,但在速度方面,普通的命令式循环在Python中是无可匹敌的。

3

试试:

def largest():
    f = pickAFile()
    sound = makeSound(f)
    value = []
    for i in range(1, getLength(sound)):
      value.append(getSampleValueAt(sound, i))
    print max(value)

或者

def largest():
    f = pickAFile()
    sound = makeSound(f)
    print max(getSampleValueAt(sound, i) for i in range(1, getLength(sound)))

在你的代码中,value 在每次循环时都会被覆盖。如果你把所有的值放到一个列表里,就可以用 max 来找到最大值。

另外可以看看:

撰写回答