簡體   English   中英

Python,創建一個程序來從文件中讀取數字並計算總和

[英]Python, creating a program that reads numbers from file and calculates the sum

我的文件僅包含數字:

22 33 56 2 1.4 67.4
34.5 49 11.2 

我想用python代碼創建一個程序,該程序讀取帶有數字的文件(不必是這個文件),然后計算這些數字的總和。

有誰知道該如何進行?

okej,因此在您的幫助下,我嘗試根據到目前為止在課堂上學到的知識來制作自己的版本:

my_file = open("mesurements.txt", "r")

sum1 = 0

for line in my_file.readlines():

    line = line.strip("\n").split()

    for i in line:

        sum1 += float(i)

print(sum1)

您認為這樣的事情是正確的嗎(對我有用,但是maby可能會犯一些錯誤?)

這是您的工作答案:

values = [float(x) for x in open('demo.txt').read().split()]
print sum(float(i) for i in values)

假設文件numbers.txt包含您的號碼:

22 33 56 2 1.4 67.4
34.5 49 11.2

嘗試以下操作來計算文件中所有數字的總和:

def sum_file(file):
    with open(file, "r") as f:
        return sum([sum([float(x) for x in line.strip().split(' ')]) for line in f])

#print the result
print("{0:.2f}".format(sum_file("numbers.txt")))

測試6x6矩陣:

9.54 3.62 9.13 9.24 6.94 1.61
2.32 1.72 8.06 8.89 9.21 6.06
4.46 3.42 8.44 4.83 9.90 1.84
2.38 6.83 7.04 9.66 1.53 8.92
3.06 9.02 8.69 7.18 9.18 1.29
1.55 7.57 9.20 3.90 3.84 2.56

sum_file("numbers.txt")結果為212.63

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM