2016-04-27 48 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