这是我到目前为止所做的,但它不起作用:
def InsertInsideTheTopPlayer (name, time):
players = []
with open("playersScores.txt") as f:
for line in f:
name, time = line.split(',')
time = float(time)
players.append((name, time))
players.sort(key=lambda s: s[1])
strtime = str(time)
for name, time in players:
f.write("%s\n" % (name+", "+ strtime))
name
是一个字符串,time
是一个浮点数(四舍五入到小数点后两位)。
经过一些编辑后,这就是我所拥有的:
def InsertInsideTheTopPlayer (name, time):
players = []
strtime = str(time)
players.append((name, strtime))
with open("playersScores.txt", "r") as f:
for line in f:
name, strtime = line.split(',')
players.append((name, strtime))
f.close()
players.sort(key=lambda tup: tup[1])
with open("playersScores.txt", "w") as f:
for (name, strtime) in players:
f.write("%s\n" % (name+","+ strtime))
f.close()
它适用于2次迭代然后给出:
line 10, in <module>
players.append((name, strtime))
builtins.ValueError: need more than 1 value to unpack
看来排序会添加空行 任何人都可以指出我如何解决这个问题的正确方向吗?
移动线8&amp; 9进入if line != '\n':
是一种解决方法,但我不知道如何阻止空行发生。
if line != '\n':
name, strtime = line.split(',')
players.append((name, strtime))
答案 0 :(得分:1)
有几个问题:
players = [(name, time)]
之一开始,或者在循环之后拥有players.append((name, time))
f
(使用f.close()
)然后重新打开它以进行书写。