使用列表推导来存储最大值

Vod*_*Vod 1 python list-comprehension

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

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]
Run Code Online (Sandbox Code Playgroud)

Mos*_*oye 5

您可以使用Python 3中itertools.accumulatemax内置:

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]
Run Code Online (Sandbox Code Playgroud)


Wil*_*sem 5

您在这里展示的是函数式编程中所谓的典型形式scan

使用列表理解来实现此目的的一种低效方法是:

[max(input[:i]) for i in range(1,n+1)]
Run Code Online (Sandbox Code Playgroud)

但这将在O(n 2 )中运行。

如果您使用具有副作用的函数,则可以使用列表理解来执行此操作:如下所示:

def update_and_store(f,initial=None):
    cache = [initial]
    def g(x):
       cache[0] = f(cache[0],x)
       return cache[0]
    return g
Run Code Online (Sandbox Code Playgroud)

然后您可以使用:

h = update_and_store(max,a[0])
[h(x) for x in a]
Run Code Online (Sandbox Code Playgroud)

或者您可以使用字典,setdefault()例如:

def update_and_store(f):
    c = {}
    def g(x):
        return c.setdefault(0,f(c.pop(0,x),x))
    return g
Run Code Online (Sandbox Code Playgroud)

并用以下方式调用它:

h = update_and_store(max)
[h(x) for x in a]
Run Code Online (Sandbox Code Playgroud)

就像@AChampion说的。

但带有副作用的函数相当不符合Python风格,也不是声明性的

但您最好使用一种scanlaccumulate方法,例如以下提供的方法itertools

from itertools import accumulate

accumulate(input,max)
Run Code Online (Sandbox Code Playgroud)