Python 列表索引必须是整数而不是str(可能很容易回答)

Python 列表索引必须是整数而不是str(可能很容易回答),python,Python,我最近在前一篇文章中问了一个关于高分的问题。这是一个类项目,因此应该相对简单。我仍然是这个网站的新手,所以我不确定如何干净地发布新的修订版本,所以如果你已经阅读了部分内容,我道歉。这次我只想把整个程序放在这里。除高分部分外,一切正常。当我选择在玩游戏之前只检查高分列表时,输出效果很好,但是,玩游戏后,返回主菜单,然后再次检查高分,我得到的错误是 列表索引必须是整数而不是str 。我想这意味着我的原始分数表设置不正确,但我不能完全确定。这是代码,我非常感谢您的帮助。这个网站对于这样的人来说太棒了

我最近在前一篇文章中问了一个关于高分的问题。这是一个类项目,因此应该相对简单。我仍然是这个网站的新手,所以我不确定如何干净地发布新的修订版本,所以如果你已经阅读了部分内容,我道歉。这次我只想把整个程序放在这里。除高分部分外,一切正常。当我选择在玩游戏之前只检查高分列表时,输出效果很好,但是,玩游戏后,返回主菜单,然后再次检查高分,我得到的错误是

列表索引必须是整数而不是str

。我想这意味着我的原始分数表设置不正确,但我不能完全确定。这是代码,我非常感谢您的帮助。这个网站对于这样的人来说太棒了

import random
loop_game = True

while loop_game:
    questions= [
                {"question": "Who won the 2012 NFL Superbowl?",
                 "answers": ["Jacksonville Jaguars",
                            "Oakland Raiders",
                            "New York Giants",
                            "Baltimore Ravens"],
                 "correct": "4"},
                {"question": "Which song was at the top of the charts in early 2001, by OutKast?",
                 "answers": ["Bootylicious",
                             "Angel",
                             "Ms. Jackson",
                             "U Got It Bad"],
                "correct": "3"},
                {"question": "How many centimeters are one inch?",
                 "answers": ["2.12",
                             "2.54",
                             "3.24",
                             "3.38"],
                "correct": "2"}]

    scores=[{'initials': None,
             'score': -500}]

#main menu
    def main_menu():
        global loop_game
        print("""
***********************************************  
Welcome to The Greatest Trivia Show on Earth!!!
***********************************************
1. Play Game
2. High Scores
3. Credits
4. Instuctions
5. Quit
""")
        needs_input = True
        while needs_input:
          selection = input("Which Selection would you like? ")
          if selection == "1":
              play_game()
              needs_input = False
          elif selection == "2":
              display_scores()
              needs_input = False
          elif selection == "3":
              credits()
              needs_input = False
          elif selection == "4":
              instructions()
              needs_input == False
          elif selection == "5":
              needs_input = False
              loop_game = False
          else:
              print("\nSelect a valid option\n")

    def play_game():
        #definitions
        global total_points
        global questions
        loop_pa = True
        total_points = 3
        random.shuffle(questions)
        counter = 0
        #gets name in case of high score
        global hs_name
        hs_name = input("What are your initials?: ")


        #main play loop
        while counter < 2:
            for j in questions:
                counter += 1
                print("\n",j["question"])
                for i, choice in enumerate(j["answers"]):
                    print(str(i+1) + ". " + choice)
                answer = str(input("\nChoose an answer 1-4: "))
                if answer == j["correct"]:
                    print("\nGood job! You keep your precious points...this time!\n")
                else:
                    print("\nSorry, that is not correct. You lose one point.\n")
                    total_points -= 1
                    print("\nTotal Points: ",  total_points)

        #all questions have been read
        print("\nThat's it, your score is: ", total_points)

        #check/append best scores list
        best_scores()

        #keep playing loop
        while loop_pa:
            keep_playing = input("Play again?  (y, n) \n")
            if keep_playing == "y":
                print("\nAwesome! Here we go! \n\n")
                loop_pa = False
                play_game()
            elif keep_playing == "n":
                print("Ahh, too bad.  Thanks for playing!")
                loop_pa = False
                main_menu()
            else:
                print("Select a valid option\n")

    def best_scores():
        for i, score in enumerate(scores):
            if total_points > score['score']:
                scores[i:i+1] = {'initials': hs_name, 'score': total_points}
                del scores[5:]
                break

    def display_scores():
        print("HIGH\tSCORES")
        for score in scores:
            print(score['initials'], "\t", score['score'])

    def instructions():
        print("""

*************
Instructions
*************
The game is quite simple:  You start out with 12 points.
You lose a point for every incorrect answer.
If you get an answer correct, your score stays the same
and you move forward through the question set.  Try to
see how many points you can keep!
         """)
        main_menu()

    def credits():
        print("\nCreated by Jessica Gregg and Jason Vignochi\n")
        main_menu()


    main_menu()
随机导入
loop_game=True
当你玩游戏时:
问题=[
{“问题”:“谁赢得了2012年NFL超级碗?”,
“答案”:[“杰克逊维尔美洲虎”,
“奥克兰袭击者”,
“纽约巨人”,
“巴尔的摩乌鸦”],
“正确”:“4”},
{“问题”:“奥特卡斯特在2001年初的排行榜上,哪首歌名列榜首?”,
“答案”:[“淫荡”,
“天使”,
“杰克逊女士”,
“你做得很糟”],
“正确”:“3”},
{“问题”:“一英寸等于多少厘米?”,
“答案”:[“2.12”,
"2.54",
"3.24",
"3.38"],
“正确”:“2”}]
分数=[{姓名首字母]:无,
“分数”:-500}]
#主菜单
def主菜单():
全局循环博弈
打印(“”)
***********************************************  
欢迎来到地球上最伟大的琐事秀!!!
***********************************************
1.玩游戏
2.高分
3.学分
4.指示
5.退出
""")
需要输入=真
虽然需要_输入:
选择=输入(“您想要哪个选择?”)
如果选择==“1”:
玩游戏
需要输入=False
elif选择==“2”:
显示分数()
需要输入=False
elif选择==“3”:
学分()
需要输入=False
elif选择==“4”:
指示()
需要\u输入==False
elif选择==“5”:
需要输入=False
loop_game=False
其他:
打印(“\n选择一个有效选项\n”)
def play_game():
#定义
全球总分
全球问题
循环_pa=True
总分=3分
随机。随机(问题)
计数器=0
#获取高分情况下的名称
全局hs_名称
hs_name=input(“您的姓名首字母是什么?:”)
#主播放循环
当计数器<2时:
对于有问题的j:
计数器+=1
打印(“\n”,j[“问题”])
对于i,枚举中的选择(j[“答案]):
打印(str(i+1)+“+”选项)
答案=str(输入(“\n选择答案1-4:”)
如果答案==j[“正确”]:
打印(“\n好工作!您保留了宝贵的积分…这次!\n”)
其他:
打印(“\n检查,这不正确。您丢了一分。\n”)
总分-=1
打印(“\n总分:”,总分)
#所有问题都已阅读
打印(“\n就是这样,你的分数是:”,总分)
#检查/附加最佳分数列表
最佳成绩
#保持循环
而loop_pa:
继续播放=输入(“再次播放?(y,n)\n”)
如果继续播放=“y”:
打印(“\nAwesome!开始了!\n\n”)
循环_pa=False
玩游戏
elif keep_playing==“n”:
打印(“啊,太糟糕了,谢谢你玩!”)
循环_pa=False
主菜单()
其他:
打印(“选择有效选项\n”)
def最佳_分数():
对于i,枚举中的分数(分数):
如果总分>分数['score']:
分数[i:i+1]={姓名首字母:hs_姓名,'score':总分}
del分数[5:]
打破
def显示_分数():
打印(“高\t存储”)
对于分数中的分数:
打印(分数['score'],“\t”,分数['score'])
def指令():
打印(“”)
*************
说明书
*************
游戏很简单:你先得12分。
每答错一题,你就丢一分。
如果答案正确,你的分数保持不变
然后你就可以通过问题集继续前进。试着
看看你能保留多少积分!
""")
主菜单()
def credits():
打印(“\n由Jessica Gregg和Jason Vignochi创建\n”)
主菜单()
主菜单()
编辑:哦!错误所在的行在显示分数功能中(第119行) 打印(分数['score'],“\t”,分数['score'])


问题在于这一行:

scores[i:i+1] = {'initials': hs_name, 'score': total_points}
替换序列的子片段时,必须用另一个iterable替换它。例如:

>>> a = [0, 1, 2, 3, 4]
>>> a[2:3] = [3] # fine
>>> a[2] = 3 # fine
>>> a[2:3] = 3
TypeError: can only assign an iterable
那么,为什么您的代码不是一个
TypeError
?因为dict实际上是一个iterable,它的行为就像一个键列表。因此,当您试图用字典替换子列表
[{'s initials':old_name,'score':old_score}]
时,
{'s initials':new_initials,'score':new_score}
,它实际上看到的是
['initials',score']

那么,拉特
def best_scores():
    global scores
    for i, score in enumerate(scores):
        if total_points > score['score']:
            scores.insert(i, {'initials': hs_name, 'score': total_points})
            scores = scores[:5]
            break
from operator import itemgetter

def best_scores():
    global scores
    scores.append({'initials': hs_name, 'score': total_points})
    scores = sorted(scores, key=itemgetter('score'), reverse=True)[:5]