python - 如何根据 xrange() 的输出添加值?

标签 python

我不确定标题的措辞是否正确,但我想做的是找到 xrange() 传递的值的总和。

理想情况下,它看起来像这样:(注意,这不是工作代码)

mofthree = xrange(2, 1000, 3)
moffive = xrange(4, 996, 5)

print mofthree + moffive

当然,您不能将两个函数加在一起。我也可以做一些事情,例如将 moftree 中的所有值加在一起,将结果存储在一个新变量中,然后对 moffive 做同样的事情并将两个新变量加在一起。

但是,我根本不知道如何将这些值以任何一种方式相加。

最佳答案

mofthree = xrange(2, 1000, 3)
moffive = xrange(4, 996, 5)

print sum(mofthree) + sum(moffive)

或者使用 itertools 和 chain

from itertools import chain
mofthree = xrange(2, 1000, 3)
moffive = xrange(4, 996, 5)

print sum(chain(moffive, mofthree))

关于python - 如何根据 xrange() 的输出添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661954/

相关文章:

python - 无法让 mysql 与 django 一起工作

Python、SQLAlchemy 和 Postgresql : understanding inheritance

python - 加载 ipython qtconsole 时出错

python - 同时运行多个python脚本

python - 根据Django中过滤的列提取最新记录的查询集

python - UnpicklingError : pickle data was truncated when trying to read a dictionary from a shelved file

python - 避免重复将多个字符串转换为 float

python - 紧随其后提取子字符串 - 在 Python 中

python - 如何验证何时使用 Python 制作副本?

python - 将特征哈希应用于 DataFrame 中的特定列