【问题标题】:Python 3.6: List indices must be integers or slices, not tuplesPython 3.6:列表索引必须是整数或切片,而不是元组
【发布时间】:2018-02-27 03:25:24
【问题描述】:

我是 Python 新手,正在尝试填空测验。我已经在不同的论坛中研究了这个错误,但仍然无法纠正我的代码。我觉得我应该能够做到这一点,但我只是看不到答案。错误在代码底部的 def game_start 函数中。这是repl.it https://repl.it/LN4r/5。这是错误:

Traceback (most recent call last):
File "python", line 62, in <module>
File "python", line 59, in game_start
TypeError: list indices must be integers or slices, not tuple

这是我的代码:

# quizzes below are in order, top to bottom, easy, medium, hard
quizzes = [
    ['''The keyword def is used to define a ___1___ . A function can be used to replace many instances of a ___2___ in a program. The use of if and ___3___ are helpful in declaring an either/or scenario. When you want a loop to be run until a condition is met, the ___4___ is helpful.'''],
['''When writing Python code, indentation must be ___1___ spaces. Also, a ___2___ must be placed at the end of a function. The ___3___ command can be used to query the user. When using parentheses, double or ___4___ ones can be used.'''],
['''What does "d = {}" create? ___1___\n In this example: "x = {"apple":2}" What is the key? ___2___\n What will: "wheel".replace("e","l") output? ___3___\n list1 = [4,2] What is list1 * 2?(include brackets)___4___''']
    ]

# answers for all quizzes.
quiz_answers = [
    ['dictionary', '2', 'whlll', '[4,2,4,2]'],
    ['four', 'colon', 'input', 'single'],
    ['function', 'loop', 'else', 'while']
    ]   

# player level selection
def level_chosen():
    chosen_level = str(input('Please select a level: easy, medium, hard: '))
    if chosen_level == 'easy':
        print("You have chosen easy. Let's play!")
        return quizzes[0], quiz_answers[0]

    elif chosen_level == 'medium':
        print("You have chosen medium. Let's play!")
        return quizzes[1], quiz_answers[1]

    elif chosen_level == 'hard':
        print("You have chosen hard. Let's play!")
        return quizzes[2], quiz_answers[2]

    else:
        print('Not a valid option. Try again.')  
        return level_chosen()

def fill_in_blanks(chosen_level, blank_location = 1, filled_blanks = 0):
    blanks = 4
    while filled_blanks < blanks:
        user_input = input("What is your answer for ___" + str(filled_blanks + 1) + "___?")
        if right_answer(chosen_level, blank_location, user_input):
            if blank_location >= blanks:
                print('You have answered them all correctly!')
                show_new_sentence(chosen_level, blank_location)
            print('Goodjob! Next blank...')
            filled_blanks += 1
            blank_location += 1
        else:
            print('Please try again.')
            fill_in_blanks(chosen_level, blank_location, filled_blanks)

def right_answer(chosen_level, blank_location, answer):
    return str(answer) == quiz_answers[chosen_level][blank_location - 1]

def show_new_sentence(chosen_level, location):
    replace_location = 1
    while replace_location <= location:
        quizzes[chosen_level] = quizzes[chosen_level].replace('___' + str(replace_location) + '___', quiz_answers[chosen_level][replace_location - 1])
        replace_location += 1
    print(quizzes[chosen_level])


def game_start():
    print('Hello! Welcome to my quiz!')
    while True:
        chosen_level = level_chosen()
        print(quizzes[chosen_level])
        fill_in_blanks(chosen_level)

game_start()

【问题讨论】:

  • 如果您需要帮助调试某些东西,请提供minimal reproducible example,不要忘记minimal
  • 这里有很多代码我不打算介绍,但我猜你用作列表索引的任何东西都是元组而不是整数或切片。在这里只是在黑暗中拍摄。
  • 你的 level_cosen() 方法返回一个 (quizzes[#],quiz_answers[#]) 元组

标签: python list tuples typeerror indices


【解决方案1】:

尝试用这个替换你的 level_chosen 函数。

def level_chosen():
    chosen_level = str(input('Please select a level: easy, medium, hard: '))
    if chosen_level == 'easy':
        print("You have chosen easy. Let's play!")
        l = [quizzes[0], quiz_answers[0]]
        return l

    elif chosen_level == 'medium':
        print("You have chosen medium. Let's play!")
        l = [quizzes[1], quiz_answers[1]]
        return l

    elif chosen_level == 'hard':
        print("You have chosen hard. Let's play!")
        l = [quizzes[2], quiz_answers[2]]
        return l

    else:
        print('Not a valid option. Try again.')
        return level_chosen()

在您的函数“level_chosen”中,您的返回值被转换为元组。要解决此问题,请尝试将“return item1, item2”替换为“return list(item1, item2)”或“return [item1, item2]”。

元组是不可变的,即它们一旦创建就不能更改。这里唯一的问题是你想指定你不想要一个元组,而是一个列表(它是可变的)。在元组周围添加函数 list() 会将其转换为列表。

【讨论】:

  • 谢谢大家! Ethan,你的回答很有帮助,我得到了它的工作。
猜你喜欢
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2017-10-02
  • 2019-09-15
  • 1970-01-01
相关资源
最近更新 更多