汇总一串字符串

时间:2019-03-20 14:46:02

标签: python python-3.x

我有一个文件,其中有一堆数字(35463)。我想找到所有数字的总和,但是所有数字都定义为字符串。 我知道可以通过float()将字符串转换为数字,但是由于它具有35463个字符串,因此将所有字符串都转换为数字将非常繁琐。 到目前为止,我写的是这样:

def main():
    with open ("file", "r") as myfile:
        data = myfile.read().splitlines()

main()

2 个答案:

答案 0 :(得分:1)

如果文件的每一行上只有一个数字,例如

0.7506097252963208
0.9176088653062778
0.6762574457637649
0.9782545470065891
...

您可以通过循环打开文件对象来循环浏览文件的各行。在这里,我使用mapfloat应用于文件的每一行

with open('filename') as f:
    result = sum(map(float, f))

我尝试了350000个条目,大约花了145毫秒(在不是很好的计算机上)。

答案 1 :(得分:0)

假设您已经创建了一个数字文件,如下所示:

echo "1234\n2545353\n123245\n3254657687\n8976857463\n" >> numbers.txt

看起来像这样:

cat numbers.txt                                                                             
1234
2545353
123245
3254657687
8976857463

一种可能的解决方案:

# read the lines and trim them
lines = list(map(str.strip, open('numbers.txt').readlines()))
# ['1234', '2545353', '123245', '3254657687', '8976857463', '']

# remove line ending, empty lines
lines = list(filter(lambda item: len(item), nums))
# ['1234', '2545353', '123245', '3254657687', '8976857463']

# convert to numbers
nums = list(map(float, lines))
# [1234.0, 2545353.0, 123245.0, 3254657687.0, 8976857463.0]

# and now we simply sum 'em
total = sum(nums)
# 12234184982.0
相关问题