Skip to main content
 首页 » 编程设计

python之使用列表理解来存储最大可见值

2025年05月04日12exmyth

是否可以通过列表理解来执行以下操作?尝试存储在循环中任何给定点看到的最大值。

def test(input): 
    a = input[0] 
    b = [] 
    for i in input: 
        a = max(i,a) 
        b.append(a) 
    return b 
 
print test([-5,6,19,4,5,20,1,30]) 
 
# returns [-5, 6, 19, 19, 19, 20, 20, 30] 

请您参考如下方法:

您可以使用 itertools.accumulate与 max内置于 Python 3:

from itertools import accumulate 
 
lst = [-5,6,19,4,5,20,1,30] 
r = list(accumulate(lst, max)) #[i for i in accumulate(lst, max)] 
print(r) 
# [-5, 6, 19, 19, 19, 20, 20, 30]