【问题标题】:Python sum certain values from multiple text filesPython对来自多个文本文件的某些值求和
【发布时间】:2019-11-18 02:35:12
【问题描述】:

我有多个包含多行浮点数的文本文件,每行有两个用空格分隔的浮点数,例如: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' object is not iterable。我一直在用这个把头发拉出来,不知道该怎么办,有人能帮忙吗?

【问题讨论】:

    标签: python python-3.x text-files


    【解决方案1】:

    我会这样做:

    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', '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))
    

    【讨论】:

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