Python将多个文本文件中的某些值相加

我有多个包含多行浮点数的文本文件,每行有两个由空格分隔的浮点数,如下所示:1.123 456.789123。我的任务是总结每个文本文件中空格之后的浮点数。必须对所有行都执行此操作。例如,如果我有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”对象不可迭代。我一直在用这种方法拔头发,不知道该怎么办,有人可以帮忙吗?

ccc_crazy_2000 回答:Python将多个文本文件中的某些值相加

这是我要怎么做:

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内可能更合乎逻辑,例如:

yield [float(x) for x in line.strip().split()]

但是我要由您决定如何更改它。

See it in action

-编辑-

请注意,上述解决方案在进行数学运算之前将所有文件加载到内存中(我这样做是为了打印结果),但是由于open_file生成器的工作原理,您不需要这样做,这是一个对内存更友好的版本:

# More memory friendly solution:
# Note that the `result` iterator will be consumed by the `for` loop.
files = ('text1.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))
本文链接:https://www.f2er.com/3085460.html

大家都在问