我有多个文本文件,其中包含多行 float ,每行都有两个由空格分隔的 float ,如下所示:1.123 456.789123。我的任务是对每个文本文件中的空格后的 float 求和。必须对所有线路执行此操作。例如,如果我有 3 个文本文件:
1.213 1.1
23.33 1
0.123 2.2
23139 0
30.3123 3.3
44.4444 444
现在第一行的数字之和应该是 1.1 + 2.2 + 3.3 = 6.6。第二行的数字总和应该是 1 + 0 + 444 = 445。我尝试了这样的方法:
def foo(folder_path):
contents = os.listdir(folder_path)
for file in contents:
path = os.path.join(folder_path, file)
with open(path, "r") as data:
rows = data.readlines()
for row in rows:
value = row.split()
second_float = float(value[1])
return sum(second_float)
当我运行代码时,出现此错误:TypeError:“float”对象不可迭代。我一直在为此烦恼,不知道该怎么办,有人可以帮忙吗?
最佳答案
这是我的做法:
def open_file(file_name):
with open(file_name) as f:
for line in f:
yield line.strip().split() # Remove the newlines and split on spaces
files = ('text1.txt', 'text2.txt', 'text3.txt')
result = list(zip(*(open_file(f) for f in files)))
print(*result, sep='\n')
# result is now equal to:
# [
# (['1.213', '1.1'], ['0.123', '2.2'], ['30.3123', '3.3']),
# (['23.33', '1'], ['23139', '0'], ['44.4444', '444'])
# ]
for lst in result:
print(sum(float(x[1]) for x in lst)) # 6.6 and 445.0
将值强制转换为在 open_file
内 float 可能更符合逻辑,例如:
yield [float(x) for x in line.strip().split()]
但这取决于你想如何改变它。
-- 编辑--
请注意,上述解决方案在进行数学计算之前将所有文件加载到内存中(我这样做是为了打印结果),但由于 open_file
生成器的工作原理,您不需要为此,这里有一个更内存友好的版本:
# More memory friendly solution:
# Note that the `result` iterator will be consumed by the `for` loop.
files = ('text1.txt', 'text2.txt', 'text3.txt')
result = zip(*(open_file(f) for f in files))
for lst in result:
print(sum(float(x[1]) for x in lst))
关于Python 对多个文本文件中的某些值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903298/