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

2024-09-30 18:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个简单的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'  

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


Tags: columnscsvtheinfordataopenfloat
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]

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

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

在存储到data列表之前,应该先转换为floatint。示例-

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

相关问题 更多 >