我试图接受一个用户输入,然后将该输入转换为一个变量以打印出一个列表。
food_list = ["Rice", "l2", "l3"]
Rice = []
l2 = []
l3 = []
answer = input("What item would you like to see from the list")
if answer in food_list:
print("answer")
我希望输出是打印Rice列表,而不仅仅是字符串";大米";就像过去一样。输入会将其作为字符串,但我想将输入转换为列表变量。
您可以使用字典:
~/tests/py $ cat rice.py
food_list ={"Rice":"Rice is nice" }
print("What item would you like to see from the list")
answer = input(": ")
if answer in food_list.keys():
print(food_list[answer])
~/tests/py $ python rice.py
What item would you like to see from the list
: Rice
Rice is nice
Python的in
关键字功能强大,但它只检查列表成员身份。
你想要这样的东西:
food_list = ["Rice", "Cookies"]
answer = input("What item would you like to see from the list")
# if the food is not in the list, then we can exit early
if answer not in food_list:
print("Food not found in the list")
# we know it's in the list, now you just filter it.
for food in food_list:
if food == answer:
print(food)
编码快乐!