2016-12-06 118 views
-5

所以我proffessor已經assinged我們用Python語言編寫一個文件,其中包含這個..Python文件(讀/寫)

37107287533902102798797998220837590246510135740250 
46376937677490009712648124896970078050417018260538 
74324986199524741059474233309513058123726617309629 
91942213363574161572522430563301811072406154908250 
23067588207539346171171980310421047513778063246676 
89261670696623633820136378418383684178734361726757 
28112879812849979408065481931592621691275889832738 
44274228917432520321923589422876796487670272189318 
47451445736001306439091167216856844588711603153276 
70386486105843025439939619828917593665686757934951 

Then..we必須逐行閱讀並seprately總結每一行所以最後它會是這樣的..

37107287533902102798797998220837590246510135740250 SUM: 214 
46376937677490009712648124896970078050417018260538 SUM: 226 
..etc... 

需要幫助解決這個問題。

P.S他還將此添加爲小費(lines = f.readlines()) 另外,如果可能的話,嘗試幫助一些基本的Python,因爲我們仍然是初學者。

+1

到目前爲止你做了什麼?向我們展示你的嘗試和任何問題 – depperm

回答

0

您最好的解決方案是讀取每行(使用提示讀取線)。記得readlines()會爲你提取所有的行並將它們存儲在一個字符串行列表中。

lines = <filename>.readlines() 
# Lines now holds and array of lines read by the file 
# lines[0] = 37107287533902102798797998220837590246510135740250 
# lines[1] = 46376937677490009712648124896970078050417018260538 

現在您已經添加了數行,然後遍歷該行中的每個字符,並將其轉換爲數字並且具有累計總數。

# Go through each line 
for line in lines: 
    total = 0 
    # Go through each letter of that line (i.e. 3 then 7 then 1....) 
    for letter in line: 
      # Cast that letter to a number and add it to the total 
      total += int(letter) 
    # Append to the end of your line 
    line += " SUM " + str(total) 

使用python,只需幾行即可完成此任務。我將把開放的文件留給你!

+0

如果是「只有幾行」,我會建議這樣做:'sum(map(int,line))' – Matthias