简体   繁体   English

总结一串字符串

[英]Summing bunch of string numbers

I have a file which has bunch of numbers(35463) in it. 我有一个文件,里面有一堆数字(35463)。 I want to find the sum of all the numbers, but all the numbers are defined as strings. 我想找到所有数字的总和,但是所有数字都定义为字符串。 I know that strings can be turned into an number by float() but as it has 35463 strings, it will be so much work to turn all the strings to numbers, each by each. 我知道可以通过float()将字符串转换为数字,但是由于它具有35463个字符串,因此将所有字符串都转换为数字将非常繁琐。 I wrote this so far: 到目前为止,我写道:

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

main()

If your file just has a number on each line, eg 如果文件的每一行上只有一个数字,例如

0.7506097252963208
0.9176088653062778
0.6762574457637649
0.9782545470065891
...

You can loop through the lines of the file by looping over the open file object. 您可以通过循环打开文件对象来循环浏览文件的各行。 Here I use map to apply float to every line of the file 在这里,我使用mapfloat应用于文件的每一行

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

I tried with 350000 entries and it took about 145 milliseconds (on a not very good computer). 我尝试了350000个条目,大约花了145毫秒(在不是很好的计算机上)。

Let's say you have create a file of numbers like this: 假设您已经创建了一个数字文件,如下所示:

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

looks like this: 看起来像这样:

cat numbers.txt                                                                             
1234
2545353
123245
3254657687
8976857463

one possible solution: 一种可能的解决方案:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM