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

时间:2015-10-10 03:58:22

标签: 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:不支持的操作数类型 - :' 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'  

我不知道如何解决这个问题!任何想法如何使理解工作给予应该做的事情?

2 个答案:

答案 0 :(得分:2)

代码中的问题是,在data列表(file2)的情况下,您正在从文件中读取字符串并将字符串存储到data列表中。

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

在存储到float列表之前,您应该转换为intdata。示例 -

data = []
for row in file2:
    data.append(float(row['Col1']))

答案 1 :(得分:2)

您没有将Col1值从字符串转换为float()。您可以在阅读(如下所示)或列表理解中进行转换。

data = []
for row in file2:
    data.append(float(row['Col1']))

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