2016-04-27 104 views
0

我已經開始構建一個代碼,以便按升序列出他們的測試成績以及他們的成績。它設法打印出旁邊有分數的名字,但是在它意外重複了幾個名字之後。代碼正在用逗號打印 n

info = open("resultsA.txt", "r") 
    for line in info: 
     x = line.split(",") 
     names.append(x[0]) 
     scores = x[1] + x[2] + x[3] 
     ascending = sorted(scores) 
     names.append(ascending) 
     print(*names, sep="\n") 

result

+0

'ascending'是一個列表。你可能想使用'names.extend(ascending)'(儘管如你所見,它包含一些不應該打印IMO的換行符和空格) –

+0

可能你也想'scores = x [1], x [2],x [3]' –

+0

非常感謝。與逗號和\ n的問題進行了排序,但我不明白爲什麼它再次打印相同的名稱和分數。 – Nightly

回答

0

你循環做兩件事情。首先,它向names列表(排序分數的另一個列表以及單個字符串)附加一些新值。然後它打印列表的內容,用換行符分隔。這重複列表中的幾個項目,你可以在你的輸出看(簡寫,因爲我不能在所有的列表內容懶得打字):

Korbin   # these first two lines are from the first iteration of the loop 
[ ... ]   # 1 
Korbin   # the next four are from the second iteration 
[ ... ]   # 2 
Bob    # 2 
[ ... ]   # 2 
Korbin   # The next six are from the third iteration 
[ ... ]   # 3 
Bob    # 3 
[ ... ]   # 3 
Dylan   # 3 
[ ... ]   # 3 
Korbin   # The next eight (which I'll not show all of) are from the fourth iteration 
[ ... ]   # 4 
# etc. 

你的問題表明,這是不是你想要的。我懷疑你應該不打擾列表,並且只是在循環中直接使用print名稱和其他統計列表,或者你不應該在循環中打印,並且最後只使用一個單獨的print調用。

這裏的,只是不直接印刷在環,與你行解析固定了較小的問題一起實現:

info = open("resultsA.txt", "r") 
    for line in info: 
     x = line.strip().split(", ") # fix up the list contents 
     print(x[0]) 
     scores = x[1:4]  # don't concatenate the strings, but slice the list 
     ascending = sorted(scores) 
     print(ascending) 
+0

非常感謝,這已經完全解決了我的問題。我並不知道你能夠使用x [1:4],這使得我的任務變得更加簡單。再次感謝! – Nightly