我曾经把学生当作字典。但是,当我尝试将输入字符串与字典值(也是一个字符串)匹配时,它会显示
TypeError: string indices must be integers
此代码有什么问题?
students = {
"Male":["Jones",162,21],
"Female":["Sarah",162,18]
}
print(type(students))
for students in students.keys():
gen = input("What's your gender?: ").strip().capitalize()
if gen in students:
name =input("What's your name?: ").strip().capitalize()
if name == students[gen][0]:
print("Your name is {}").format(name)
答案 0 :(得分:0)
2 错字。 试试这个:
students = {
"Male":["Jones",162,21],
"Female":["Sarah",162,18]
}
print(type(students))
for index in students.keys():
gen = input("What's your gender?: ").strip().capitalize()
if gen in students.keys():
name =input("What's your name?: ").strip().capitalize()
if name == students[gen][0]:
print("Your name is {}".format(name))
答案 1 :(得分:0)
这就是您的代码的样子:
for student in students.keys():
gen = input("What's your gender?: ").strip().capitalize()
if gen in students.keys():
name =input("What's your name?: ").strip().capitalize()
if name == students[gen][0]:
print("Your name is {}").format(name)
您的问题是您将变量和字典命名为相同的
。答案 2 :(得分:0)
此版本对我有用:
students = {
"Male": ["Jones", 162, 21],
"Female": ["Sarah", 162, 18]
}
for student in students.keys():
gen = input("What's your gender?: ").strip().capitalize()
if gen in student:
name = input("What's your name?: ").strip().capitalize()
if name == students[gen][0]:
print(f"Your name is {name}")