Python 列表理解
可能的重复:
运行总计的列表理解
我正在尝试编写一个简洁的列表理解语句来 cdf: 例如:
print f([0.2, 0.3,0.1,0.4])
[0.2,0.5,0.6,1.0]
标准过程如下所示(我想为函数 f() 编写一个列表理解):
def f(probabilities) :
sum = 0
returnList = []
for count in probabilities:
sum +=count
returnList = returnList + [sum]
return returnList
编辑:我找到了一个函数 numpy.cumsum()。我将检查它是否使用列表理解。
Possible Duplicate:
List comprehension for running total
I'm trying to write a concise list comprehension statement to create a cdf:
For example:
print f([0.2, 0.3,0.1,0.4])
[0.2,0.5,0.6,1.0]
A standard procedure would look like this (I want to write a list comprehension for the function f()):
def f(probabilities) :
sum = 0
returnList = []
for count in probabilities:
sum +=count
returnList = returnList + [sum]
return returnList
Edit: I found a function numpy.cumsum(). I'll check if it uses list comprehensions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该操作非常常见,以至于许多语言(主要是函数式语言,但不仅仅是函数式语言)都为其提供了抽象,通常名称为
scanl
(它就像具有中间结果的reduce
) 。我们称之为 ireduce(“迭代减少”):现在使用它:
That operation is so common that many languages (mainly functional ones, but not only) provide abstractions for it, usually with the name
scanl
(it's like areduce
with intermediate results). Let's call itireduce
("iterative reduce"):And now use it:
但不要这样做,因为它的时间复杂度为 O(n^2)。 Python 列表推导式并不是为此而设计的。使用您已经编写的过程代码。
But don't do that because it's O(n^2). Python list comprehensions weren't designed for this. Use the procedural code that you already wrote.
它不是很漂亮,并且没有使用列表推导式,但是您可以使用reduce()函数来做到这一点,其中累积值是一个保存当前总和和结果列表的元组:
Python缺乏对多行lambda的支持这种丑陋的。使用单独的函数会更好:
It's not really pretty, and it's not using list comprehensions, but you can do this with the reduce() function, where the accumulated value is a tuple holding the current sum and the result list:
Python's lack of support for multi-line lambda's makes this kind of ugly. Using a separate function would be better: