Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从for循环对csv文件中的项目求和_Python_Loops_Csv_Sum - Fatal编程技术网

Python 如何从for循环对csv文件中的项目求和

Python 如何从for循环对csv文件中的项目求和,python,loops,csv,sum,Python,Loops,Csv,Sum,我被卡住了。我的脚本要求用户输入多少csv文件以及输入的字段。在本例中,假设两个csv文件各有一个面积值。我试图用for循环来总结这两项,这样我就可以尝试编写一个计算平均值的函数。尽管我每次运行它时都会遇到一个错误,即“+:int和str的操作数类型不受支持。i'v遇到了麻烦。欢迎提供帮助。” import csv Mysum = 0 input_attribute = input("Enter attribute for comparison (lowercase) :") input_Set

我被卡住了。我的脚本要求用户输入多少csv文件以及输入的字段。在本例中,假设两个csv文件各有一个面积值。我试图用for循环来总结这两项,这样我就可以尝试编写一个计算平均值的函数。尽管我每次运行它时都会遇到一个错误,即“+:int和str的操作数类型不受支持。i'v遇到了麻烦。欢迎提供帮助。”

import csv
Mysum = 0
input_attribute = input("Enter attribute for comparison (lowercase) :")
input_SetNum = input("How many data sets are you comparing: ")
print ("You entered " + input_SetNum) 

data_sets = {}
for i in range(1, int(input_SetNum)+1):
  with open(input("Please enter the file name with .csv: ")) as csvfile:
      reader = csv.DictReader(csvfile)
      for row in reader:
      data_sets[i] = (row[input_attribute])
      print (data_sets[i])


Mysum = sum(data_sets[i])
print(Mysum)

从CSV文件读入数字时,它将作为字符串读入,除非您执行以下操作:

reader = csv.DictReader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
这已经咬了我好几次了

答案要么是将
阅读器
创建为
csv.QUOTE\u NONNUMERIC
,要么使用
int()
str
显式转换为
int
。如果不查看数据文件的实际示例以查看它们的格式,很难说哪种方法更好

另外,请注意,您仍然存在一些格式问题,如问题的前几次迭代:

import csv
Mysum = 0
input_attribute = input("Enter attribute for comparison (lowercase) :")
input_SetNum = input("How many data sets are you comparing: ")
print ("You entered " + input_SetNum) 

data_sets = {}
for i in range(1, int(input_SetNum)+1):
  with open(input("Please enter the file name with .csv: ")) as csvfile:
      reader = csv.DictReader(csvfile)
      for row in reader:  # The code in your `for` block needs to be indented or you're going to get more errors...
          data_sets[i] = (row[input_attribute])
          print (data_sets[i])


Mysum = sum(data_sets[i])
print(Mysum)

数据文件非常简单,它们都只有一个区域和一个单元格值。它们有标题吗?如果没有,那么您可能不想使用
csv.DictReader()
,您可能想使用
csv.reader()
。是的,它们的标题描述了它是什么字段。通过编写Mysum=Mysum+int来改变它(数据集[i])感谢您的帮助,这是有意义的——您已显式转换为
int
。使用
csv打开您的读卡器。引用非数字的
将其转换为
float
,并允许您添加它们。