file = open("1.txt")
classj = (file.readlines())
s = []
for line in sorted(classj):
classj = (line.rstrip())
classa = (classj.split("-"))#sort
score = int(classa[1])
name = (classa[0])
s.append( (name,score) )
s.sort(reverse=True, key=lambda x:x[1])
for x in s:
print(x[0],"-",x[1])
我有一个文本文件的内容,其中我有分数,我需要从高到低排序,但它最初只打印分数,但现在我得到的消息列表索引超出范围
答案 0 :(得分:-1)
您的文件有一些行,其中没有-
。也许是空行?
您可以忽略空行,也可以忽略没有'-'
的行:
with open("1.txt") as inp:
s = []
for line in inp:
line = line.strip()
if not line:
continue
try:
name, score = line.split('-')
except ValueError:
print("Warning! Ignore line: %s" % line)
else:
s.append(name, int(score))
s.sort(reverse=True, key=lambda x:x[1])
for name, score in s:
print(name,"-",score)