【问题标题】:How to Properly Use Arithmetic Operators Inside Comprehensions?如何在理解中正确使用算术运算符?
【发布时间】:2023-03-28 08:25:01
【问题描述】:

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

我不知道如何解决这个问题!知道如何使理解能够给出应该做的事情吗?

【问题讨论】:

  • 错误说你不能做一个字符串减去一个浮点数。有问题的行有e-Aver。因此,e 是一个字符串,Aver 是一个浮点数。因此,您必须将e 转换为浮点数。

标签: python csv list-comprehension typeerror arithmetic-expressions


【解决方案1】:

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

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

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

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

【讨论】:

  • 谢谢!我按照您的指示进行操作,这很有意义。将数据转换为浮点类型时仍然出现错误。它说:ValueError: could not convert string to float: 有没有办法克服这个错误?
  • 这意味着您有一行在 Col1 中没有 float
  • 您是否从SumData 行收到该错误?
  • :D 是的,它正在工作! columns.csv 文件有额外的带空格的行。
  • 很高兴能为您提供帮助。如果答案有帮助,我还想请您接受答案(通过单击答案左侧的勾号),这将对社区有所帮助。
【解决方案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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多