Python 如何在理解中正确使用算术运算符?

Python 如何在理解中正确使用算术运算符?,python,csv,list-comprehension,typeerror,arithmetic-expressions,Python,Csv,List Comprehension,Typeerror,Arithmetic Expressions,我正在处理一个简单的csv文件,它包含三列和三行数字数据。csv数据文件如下所示: Col1,Col2,Col3 1,2,3 2,2,3 3,2,3 4,2,3 我很难弄明白如何让python程序从同一列中的每个值中减去第一列Col1的平均值。为便于说明,输出应给出“Col1”的以下值: 1 - 2.5 = -1.5 2 - 2.5 = -0.5 3 - 2.5 = 0.5 4 - 2.5 = 1.5 下面是我的尝试,它给了我TypeError:不支持的操作数类型-:'st

我正在处理一个简单的csv文件,它包含三列和三行数字数据。csv数据文件如下所示:

 Col1,Col2,Col3
 1,2,3
 2,2,3
 3,2,3
 4,2,3
我很难弄明白如何让python程序从同一列中的每个值中减去第一列Col1的平均值。为便于说明,输出应给出“Col1”的以下值:

1 - 2.5 = -1.5
2 - 2.5 = -0.5
3 - 2.5 =  0.5
4 - 2.5 =  1.5  
下面是我的尝试,它给了我TypeError:不支持的操作数类型-:'str'和'float' 最后打印包含理解的语句

import csv

# Opening the csv file
file1 = csv.DictReader(open('columns.csv'))
file2 = csv.DictReader(open('columns.csv'))

# Do some calculations
NumOfSamples = open('columns.csv').read().count('\n')
SumData = sum(float(row['Col1']) for row in file1)
Aver = SumData/(NumOfSamples - 1) # compute the average of the data in 'Col1'


# Subtracting the average from each value in 'Col1'
data = []
for row in file2:
    data.append(row['Col1'])

# Print the results
print Aver
print [e-Aver for e in data] # trying to use comprehension to subtract the average from each value in the list 'data'  
data = []
for row in file2:
    data.append(float(row['Col1']))

# Print the results
print Aver
print [e - Aver for e in data]

我不知道如何解决这个问题!你知道如何让理解工作来给出应该做什么吗?

代码中的问题是,对于数据列表文件2,你从文件中读取字符串并将字符串存储到数据列表中

因此,当稍后尝试执行-[e-Aver for e in data]-它会在尝试从字符串中减去float时出错

在存储到数据列表之前,应该先转换为float或int。范例-

data = []
for row in file2:
    data.append(float(row['Col1']))
您没有将Col1值从字符串转换为浮点值。您可以在阅读时进行转换,如下所示,也可以在列表中进行转换

import csv

# Opening the csv file
file1 = csv.DictReader(open('columns.csv'))
file2 = csv.DictReader(open('columns.csv'))

# Do some calculations
NumOfSamples = open('columns.csv').read().count('\n')
SumData = sum(float(row['Col1']) for row in file1)
Aver = SumData/(NumOfSamples - 1) # compute the average of the data in 'Col1'


# Subtracting the average from each value in 'Col1'
data = []
for row in file2:
    data.append(row['Col1'])

# Print the results
print Aver
print [e-Aver for e in data] # trying to use comprehension to subtract the average from each value in the list 'data'  
data = []
for row in file2:
    data.append(float(row['Col1']))

# Print the results
print Aver
print [e - Aver for e in data]

错误表示不能执行字符串减去浮点的操作。有问题的行有e-Aver。因此,e是字符串,Aver是浮点。因此,您必须将e转换为float。谢谢!我听从了你的指示,这是有道理的。当我将数据转换为浮点类型时,仍然会出现错误。它说:ValueError:无法将字符串转换为float:是否有方法克服此错误?这意味着您有一行在Col1中没有float。您是否从SumData行获得该错误?:D yahhh它正在工作!columns.csv文件有额外的一行空格。很高兴我能帮上忙。如果答案是有帮助的,我也希望你通过点击答案左侧的勾号来接受答案,这将对社区有帮助。