我试着把一个元组列表写进一个文件,然后把它们按值从低到高组织起来,但我总是遇到同样的错误。有什么办法可以做到吗?你知道吗
这是我的密码:
name = input("Please enter your name: ")
class_name = input("Which class are you in? ")
score = 0
class_name = class_name + ".txt"
f = open(class_name, 'w')
for t in class_name:
line = ' '.join(str(x) for x in t)
f.write(line + '\n')
f.close()
#See previous scores
print('Please type viewscores() to view the scores')
def viewscores():
viewscore = input("Do you wish to view previous results for your class? ").lower()
if viewscore == 'yes':
viewscore_way = input("a) Alphabetically b)Lowest to highest c)Highest to lowest? ").lower()
elif viewscore != "yes".lower():
print ("Press any key to exit")
ex = input ("")
if viewscore_way == "a".lower():
with open(class_name, 'r') as f:
lines = f.read().splitlines()
print(sorted(lines, key=str.lower))
f.close()
elif viewscore_way == "b".lower():
with open(class_name, 'r') as fp:
lines = [line.strip() for line in fp]
data = [tuple(line.split(',')) for line in lines]
sorted_by_second = sorted(data, key=lambda tup: tup[1])
print(sorted_by_second)
f.close()
elif viewscore_way == "c".lower():
print(sorted(data,key=itemgetter(1), reverse = True))
但是,当我运行我的代码时,我得到了一个错误
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
viewscores()
File "C:\Users\Danny\Desktop\list.py", line 40, in viewscores
sorted_by_second = sorted(data, key=lambda tup: tup[1])
File "C:\Users\Danny\Desktop\list.py", line 40, in <lambda>
sorted_by_second = sorted(data, key=lambda tup: tup[1])
IndexError: tuple index out of range
如何消除“超出范围错误”并使一切正常工作?你知道吗
你用空格作为分隔符写数据,但用逗号分开读回来。你知道吗
相关问题 更多 >
编程相关推荐