简体   繁体   English

将 .csv 文件中的元素与 python 文件相加

[英]Sum elements from a .csv-file into a file with python

I am trying to use Python as a part of my uni education, and have come across a problem with a CSV-file which I hope someone can help me to solve.我正在尝试使用 Python 作为我大学教育的一部分,并且遇到了 CSV 文件的问题,希望有人可以帮助我解决。

The file consists of traffic data for several years, divided by quarters, it looks sort of like this (without the header):该文件包含几年的流量数据,按季度划分,它看起来有点像这样(没有标题):

2013;kvartal 1;10202;3;8;23\
2013;kvartal 2;10231;3;8;22\
2013;kvartal 3;8736;2;7;21\
2013;kvartal 4;11263;3;8;24\
2014;kvartal 1;9310;2;8;23\
2014;kvartal 2;12643;3;10;25\
2014;kvartal 3;12852;3;9;24\
2014;kvartal 4;8872;2;7;19

What I want to do is to sum the quarters into a new list, so that each column for each year is summed.我想要做的是将季度汇总到一个新列表中,以便将每年的每一列相加。 I would like the new list to look something like this:我希望新列表看起来像这样:

2013 - (the sum for column 3 for year 2013) - (the sum for column 4 for year 2013) - etc.

And so on for the rest of the years.以此类推为历年的rest。

To summarize I would like to sum all the quarters into single years.总而言之,我想将所有季度总结为一年。 I've managed to convert the CSV-file into a list, but all the elements are string, and thus I can't seem to sum them.我设法将 CSV 文件转换为列表,但所有元素都是字符串,因此我似乎无法对它们求和。

Does anyone have a good way of doing this?有没有人有这样做的好方法?

Thanks in advance!提前致谢!

Use a for loop on the values stored in the list and convert each one into the int using below:对存储在列表中的值使用 for 循环,并使用以下方法将每个值转换为 int:

    listnew=[]
    for i in list:
        listnew.append(int(i))
    print(sum(listnew))

try this out试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM