简体   繁体   English

如何在 itertools.accumulate 中使用初始参数?

[英]How to use initial argument inside itertools.accumulate?

In this documentation link we can read this:在此文档链接中,我们可以阅读以下内容:

itertools.accumulate(iterable[, func, *, initial=None])

Usually, the number of elements output matches the input iterable.通常,元素输出的数量与输入迭代匹配。 However, if the keyword argument initial is provided, the accumulation leads off with the initial value so that the output has one more element than the input iterable.但是,如果提供关键字参数initial ,则累积以初始值开始,因此输出的元素比输入的可迭代元素多一个。

However, I can not figure out how to use the initial argument.但是,我无法弄清楚如何使用initial参数。

If I use it like this:如果我像这样使用它:

accumulate([0, 7, 19, 13], operator.add,1)

I get error "TypeError: accumulate() takes at most 2 arguments (3 given)".我收到错误“TypeError:accumulate() 最多需要 2 个参数(给定 3 个)”。

I am using Python 3.4.我正在使用 Python 3.4。

If you look at the function signature, you notice the "*".如果您查看函数签名,您会注意到“*”。 This means anything after it should be provided as keyword arguments.这意味着它之后的任何内容都应该作为关键字参数提供。 So your call should be:所以你的电话应该是:

accumulate([0,7,19,13], operator.add, initial=1)

but you said you're using Python 3.4, then you will not have the initial argument as it is only provided in Python 3.8, as per the documentation.但是您说您使用的是 Python 3.4,那么您将没有initial参数,因为它仅在 Python 3.8 中提供,根据文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM