python – 元素方式的变量长度的总和列表
发布时间:2020-12-20 12:24:38 所属栏目:Python 来源:网络整理
导读:如果我有一个列表列表,并且每个嵌套列表都包含数字,那么如何将所有这些列表按元素添加到单个数组中? 即 listOne = [1,2,3]listTwo = [4,5,6]listThree = [7,8,9,10]allLists = [listOne,listTwo,listThree]total = add(allLists)print total 输出应该是[12,
如果我有一个列表列表,并且每个嵌套列表都包含数字,那么如何将所有这些列表按元素添加到单个数组中?
即 listOne = [1,2,3] listTwo = [4,5,6] listThree = [7,8,9,10] allLists = [listOne,listTwo,listThree] total = add(allLists) print total 输出应该是[12,15,18,10] 解决方法
使用
izip_longest 重新映射行/列(如zip但最长元素而不是最短元素),填充较短的项目0
from itertools import izip_longest total = [sum(x) for x in izip_longest(*allLists,fillvalue=0)] 输出: [12,10] 同样为了您的启发,zip_longest的中间输出是: [(1,4,7),(2,8),(3,6,9),(0,10)] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |