我是python的新手,我试图从文件中获取数据,将其放入列表中,然后获得每行的总和。我尝试剥离列表中的任何东西,但int型和浮点数,并确保文件只有数字。如果有人能帮助我,我将非常感激。感谢阅读
(问题代码)
with open("InputFileData.csv") as file:
SampleTotalHours = file.readlines();
TotalHours = []
for element in SampleTotalHours:
TotalHours.append(element.strip())
Sum = sum(TotalHours[0])
print(Sum)
(内容"InputFileData.csv"
40.1,39.7,40,38
36,36,35.5,35.8
40,41.6,40.3,40
20.4,22.8,20,20
(输出)
Traceback (most recent call last):
File "D:Assignment 6 FilesPAtest.py", line 10, in <module>
Sum = sum(TotalHours[0])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
readlines()
将返回一个字符串列表,在这种情况下,第一项是"40.1,39.7,40,38"。要得到和,首先需要用分隔符分隔字符串,并在取和之前将每个值转换为浮点数。
TotalHours = []
for element in SampleTotalHours:
hoursAsStrings = element.split(',')
hoursAsFloats = [float(hourString) for hourString in hoursAsStrings]
TotalHours.append(sum(hoursAsFloats))
TotalHours
是一个列表,其中每个值是其对应行的和。
就像这样。对于每一行,用逗号分隔,将字段转换为浮点数,将浮点数相加。您可能会发现使用csv
模块更容易,但它并没有真正为您提供这个数据集。
TotalHours = []
with open("InputFileData.csv") as file:
for line in file:
parts = [float(k) for k in line.strip().split(',')]
TotalHours.append( sum(parts) )
print(TotalHours)
这对我来说很好:
TotalHours = 0
with open("InputFileData.csv") as file:
for line in file:
for number in line.strip().split(","):
if number.replace('.', "").isnumeric():
TotalHours += float(number)
print(TotalHours)
这里有一些流行的库可供参考(一个是内置的,另一个是第三方的):
import csv
with open('InputFileData.csv', newline='') as file:
reader = csv.reader(file,quoting=csv.QUOTE_NONNUMERIC)
for row in reader:
print(row,sum(row))
输出:
[40.1, 39.7, 40.0, 38.0] 157.8
[36.0, 36.0, 35.5, 35.8] 143.3
[40.0, 41.6, 40.3, 40.0] 161.89999999999998
[20.4, 22.8, 20.0, 20.0] 83.2
import pandas as pd
df = pd.read_csv('InputFileData.csv',header=None)
df['Sum'] = df.sum(axis=1)
print(df)
输出:
0 1 2 3 Sum
0 40.1 39.7 40.0 38.0 157.8
1 36.0 36.0 35.5 35.8 143.3
2 40.0 41.6 40.3 40.0 161.9
3 20.4 22.8 20.0 20.0 83.2