使用zip_longest对不同的长度列表求和并从开始而不是结束填充不同的长度 [英] Using zip_longest to sum different length lists and fill different lengths from start rather than end

查看:56
本文介绍了使用zip_longest对不同的长度列表求和并从开始而不是结束填充不同的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表[1,2,3,4][1,2,3]

我想总结一下这些内容,以便给我以下内容:[1,3,5,7].

I would like to sum these to give me the following: [1,3,5,7].

这是通过执行1+0=12+1=33+2=54+3=7来完成的.

This was done by doing 1+0=1, 2+1=3, 3+2=5 and 4+3=7.

我知道itertools.zip_longest可以做到这一点,但最终会用0填补长度上的不匹配,给了我[2,3,6,4]而不是我想要的值.

I understand that itertools.zip_longest would do this, but it would fill the mismatch in length with 0 at the end, giving me [2,3,6,4] and not the value I want.

我希望通过用零填充第一长度来解决长度不匹配的问题.

I would like the mismatch in length to be solved by filling the first length with zero.

推荐答案

内置的

The built-in reversed() function could be used to do it like this:

from itertools import zip_longest    

def sum_lists(*iterables):
    iterables = (reversed(it) for it in iterables)
    return list(reversed([a+b for a, b in zip_longest(*iterables, fillvalue=0)]))


if __name__ == '__main__':
    result = sum_lists([1, 2, 3, 4], [1, 2, 3])
    print(result)  # -> [1, 3, 5, 7]
    result = sum_lists([1, 2, 3], [1, 2, 3, 4])
    print(result)  # -> [1, 3, 5, 7]    # Order of args doesn't matter.

这篇关于使用zip_longest对不同的长度列表求和并从开始而不是结束填充不同的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆