【问题标题】:How can I sum up same index for several different lists vertically in python 3?如何在 python 3 中垂直总结几个不同列表的相同索引?
【发布时间】:2020-10-01 18:11:04
【问题描述】:

所以我有一个 CSV 文件,它输出几个未分配给变量的数字列表,我想知道如何垂直汇总每个列表的相同索引以输出具有总和的单个列表每个列表的每个索引的垂直方向。

当前代码:

import CSV

with open('Superheroes.csv', 'r') as csvfile:
    first_line = csvfile.readline()
    super_reader = csv.reader(csvfile, delimiter=',')

for vote in super_reader:
    vote.pop(0)
    vote1 = [(x if x else '0') for x in vote]
    vote2 = list(map(int, vote1))
    print(vote2)
    
csvfile.close()

Example of lists contained in CSV file

示例: 所以对于图中显示的三个列表,我希望输出为 [18, 18, 13, 13, 11, 13, 15, 18, 13, 15, 16, 8]

有什么建议吗? 谢谢

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    使用zip

    例如:

    with open('Superheroes.csv', 'r') as csvfile:
        first_line = csvfile.readline()
        super_reader = csv.reader(csvfile, delimiter=',')
        result = []
        for vote in super_reader:
            vote.pop(0)
            result.append([int(x) if x else 0 for x in vote])
            
    result = [sum(i) for i in zip(*result)]
    print(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2021-07-22
      • 2015-12-23
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多