python - 每 3 个数字将列表中的数字相加

标签 python python-2.7

我有一个数字列表,像这样排成一行:

0
1
0
2
0
4

它有大约几千行

我想每 3 行将它们相加,这样结果将是这样的:

1
6

我已经用这一行把列表变成了单独的整数:

k = map(lambda s: s.strip(), k)
integer = map(int, k)

我怎样才能加起来?

最佳答案

使用石斑鱼,比如 Alternative way to split a list into groups of n :

import itertools

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

map(sum, grouper(3, interger, 0))

请注意,上面的代码假设是 python 2.x;对于 3.x,您需要改用 itertools.zip_longest

演示:

>>> example = [0, 1, 0, 2, 0, 4]
>>> map(sum, grouper(3, example, 0))
[1, 6]

关于python - 每 3 个数字将列表中的数字相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11738464/

相关文章:

python - 如何在 django 模板的 url templatetag 中嵌入标签?

windows - 如何用if条件写一个ini文件

python - 使用 Beautifulsoup 解析时更改 HTML 中的标签

python - 使用 zc.buildout,如何从网站安装 tarball?

python - 无法连接两个数据帧

python - IPython 中的嵌入式交互式 shell

python - 如何将 Electron 用于后端带有 Python 的图像处理应用程序?

python - 如何在 plotly 中切割子图底部的大空间?

python - 在 systemd 停止运行 python 服务之前做一些事情

python - 文档字符串中 __init__ 的返回类型