我有个问题!我试着迭代一个列表,检查一个值是否在里面,如果在里面,继续下一步,如果不在,重复输入直到用户在列表中输入一个元素
下一步,我会把我的代码,请,一些清单是做其他用途!我用的是可以吃的
DictFood = {"pasta":["spaghetti"], "meat":["beef of deer", "sasuage"], "vegetables":["chips", "letucce"], "condiment":["sugar", "salt"], "fruit":["apple", "orange"], "sweet":["chocolate"], "drink":["beer", "water"]}
TypeFood = ["pasta", "fruit", "meat", "vegetables", "condiment", "sweet", "drink"]
DictValue = {"orange":1, "spaghetti":12, "salt":0.2, "chocolate":2, "beef of deer":1, "beer":0.3, "water":0.5, "fish":3, "chips":2, "sugar":0.2, "bread":2, "apple":1, "letucce":1, "sasuage":3}
FoodAvaiable = ["orange", "spaghetti", "salt", "chocolate", "beef of deer", "beer", "water", "fish", "chips", "sugar", "bread", "apple", "letucce", "sasuage"]
x = True
def food_type():
global user_option_f
print("What do you want to buy?")
print(FoodAvaiable)
user_option_f = input()
while x == True:
if user_option_f == FoodAvaiable[0]: #here I have my doubt!! I've tried using "or" to add "FoodAvaibale[1]" and so on, and I got a infinite loop, I've tried "range(len(FoodAvaiable))" didn't worked too
x == False
print("You choose {}!".format(user_option_f))
elif user_option_f != FoodAvaiable:
print("You choose an element which is not avaiable! Please select one of the list")
print(FoodAvaiable)
print("Choose one avaiable")
input()
return user_option_f
food_type()
如何让我的用户输入遍历列表中的元素,检查它是否在列表中
抱歉,如果之前有人问过这个问题,我已经搜索了很多,但没有找到任何对我有帮助的东西。事先谢谢
您可以使用嵌套for循环来实现这一点,但正确的方法是只使用'in'操作符
我设法在一些答案的帮助下修复了代码(感谢@UnoriginalNick和@stephernauch)
在定义之外获取输入给了我一个错误,因此我最终将其写入def并对elif进行了一些调整,也许我应该改用else,但是由于这种方式看起来很稳定,所以我将保留它
相关问题 更多 >
编程相关推荐