python-将用户输入与列表进行比较,并将其附加到一个新列表中,以限制输入项
我正在用LPTHW学习python,我正在尝试构建自己的游戏作为练习36。我希望用户从10个规程中输入一个特定的字符串。我可以将输入与定义的列表进行比较,但我不能将用户限制为仅5项。相反,我可以将用户限制为只有五个输入,但不能同时进行这两个输入 我创建了规程列表(最初是字符串名称)python-将用户输入与列表进行比较,并将其附加到一个新列表中,以限制输入项,python,python-2.7,list,for-loop,compare,Python,Python 2.7,List,For Loop,Compare,我正在用LPTHW学习python,我正在尝试构建自己的游戏作为练习36。我希望用户从10个规程中输入一个特定的字符串。我可以将输入与定义的列表进行比较,但我不能将用户限制为仅5项。相反,我可以将用户限制为只有五个输入,但不能同时进行这两个输入 我创建了规程列表(最初是字符串名称) discipline_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 然后我创建了一个空列表 your_disciplines = [] 以下代码用于将用户输入与规则列表进行比较,并
discipline_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
然后我创建了一个空列表
your_disciplines = []
以下代码用于将用户输入与规则列表进行比较,并将用户输入附加到新的空列表(来自其他答案的代码)
我可以使用for循环来限制用户条目,但我不能将它与比较结合起来。我所有的尝试都运行了五次以上
for d in range(0, 5):
任何帮助都将不胜感激。如果您想在循环时使用
,您可以尝试:
num = input("Enter your disciplines number >> ") # This is not required if you want to fix num to 5
j = 0
while j < int(num):
d = raw_input("enter your choice of discipline >> ")
d = str(d)
found_d = False
for i in discipline_list:
if d == i:
found_d = True
if found_d:
your_disciplines.append(d)
else:
print("Incorrect entry")
j += 1
你可以做:
if d in discipline_list:
found_d = True
此外,您不需要使用found\u d
变量
简化的代码可以是:
num = input("Enter your disciplines number >> ")
i = 0
while i < int(num):
d = raw_input("enter your choice of discipline >> ")
d = str(d)
if d in discipline_list:
your_disciplines.append(d)
else:
print("Incorrect entry")
i += 1
num=input(“输入您的学科编号>>”)
i=0
而i>”)
d=str(d)
如果专业清单中有d:
您的_规程。附加(d)
其他:
打印(“输入错误”)
i+=1
若要组合这两种条件,请将您的
的长度检查为while
循环条件,并仅在有5个循环条件时退出
while len(your_disciplines) < 5:
d = raw_input("enter your choice of discipline >> ")
d = str(d)
if d not in your_disciplines:
your_disciplines.append(d)
else:
print("Incorrect entry")
while len(你的学科)<5:
d=原始输入(“输入您选择的规程>>”)
d=str(d)
如果d不属于您的大学学科:
您的_规程。附加(d)
其他:
打印(“输入错误”)
您的代码非常简单。我只需做一个简单的更改来检查用户条目是否在主列表中,并添加条件来检查条目是否不在新用户列表中(因此用户无法重复正确的输入)。它现在运行得很好,谢谢如果在规程列表中是d,而不是在您的规程中是d:
您的规程。附加(d)
num = input("Enter your disciplines number >> ")
i = 0
while i < int(num):
d = raw_input("enter your choice of discipline >> ")
d = str(d)
if d in discipline_list:
your_disciplines.append(d)
else:
print("Incorrect entry")
i += 1
while len(your_disciplines) < 5:
d = raw_input("enter your choice of discipline >> ")
d = str(d)
if d not in your_disciplines:
your_disciplines.append(d)
else:
print("Incorrect entry")