有没有人对如何使用输入来确定在列表中的位置有什么建议?
我正在编写代码来确定植物是否安全。在我的代码中,在用户进入他们的工厂后,我想让用户回答有关工厂的问题。回答完问题后,他们可以进入另一家工厂并重复此过程。
我的目标是为每个问题分配一个值;因此,如果用户对所有问题都回答“否”,则工厂是最安全的,如果用户对一半的问题回答“否”,则安全性减半。我会将带有四个或更多“是”的植物附加到安全的,将其他植物附加到“不安全的”。然后,我想定义另外两个函数,使用 yes 和 no 的数量打印最安全和最不安全的植物。
感谢所有评论的人!我现在有很多不同的方法可以对此进行编码。我非常感谢所有的帮助!!新的编辑反映了列表的新名称。
def plantidentifier():
print(("Enter plant or XXX to quit "))
plant = input().upper()
print("Is a mushroom")
print("Does your plant have thorns?")
print("Is your plant yellow or white?")
print ("Are there shiny leaves?")
print("Is your plant umbrella shaped?")
Good.append(plant)
Bad.append(plant)
return Good, Bad
Good = []
Bad = []
print("Welcome to plant identifier!")
print("Please cafeully consider your plants")
print("Enter the name of your first plant and start answering questions. When done entering plants, enter XXX")
plantidentifier()
回答
根据我的评论,这里有一个简单的概述,说明在这种情况下您可能想要做什么。请注意,如果您想要单个问题的结果,这将不起作用,
from distutils.util import strtobool
class Plant:
max_danger_rating = 1 # The number of questions asked
def __init__(self):
self.danger_rating = 0 # how many questions have been answered yes
is_dangerous = input("Is this plant dangerous?")
if strtobool(is_dangerous): #here is_dangerous can be "yes", "y", "t", ...
self.danger_rating += 1
plants = [] # create your plants and add them to this list
dangerous_plants = [plant for plant in plants if plant.danger_rating > Plant.max_danger_rating / 2]
safe_plants = [plant for plant in plants if plant.danger_rating <= Plant.max_danger_rating / 2]
dangerous_plants.sort(key = lambda plant: plant.danger_rating)
特别是在最后,您会注意到我们可以将danger_rating用作关键字进行排序,这使您的工作更加轻松。