python - 如何在推导式中正确使用算术运算符?

标签 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: unsupported operand type(s) for -: 'str' and '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 列表 (file2) 的情况下,您正在从文件中读取字符串并将字符串存储到 data 列表。

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

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

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

关于python - 如何在推导式中正确使用算术运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050100/

相关文章:

python - PyGears hdlgen 生成具有 DTI 接口(interface)的顶级模块,Vivado 需要 Verilog,但不支持此功能

python - Python 中的噪音?

java - 是否有任何库可以将 XLSX 文件转换为 CSV?

r - 如何编写dplyr组以分隔文件?

csv - 如何将带有计数器列的 CSV 文件加载到 Cassandra CQL3 表中

python - 将内部列表的元素相乘作为列表理解

python - 将嵌套的 for 循环转换为列表 comp 并从结果列表中过滤完全平方数

python - Pandas DataFrame 索引的自动递增选项

Elixir [42] 打印为 '*'

python - 在 Windows 上安装 SciPy 时遇到问题