【发布时间】:2021-08-11 06:51:03
【问题描述】:
我有一个问题,我需要将在森林中发现的物种分类到不同的列表中。到目前为止,这是我的代码:
# we assume these to be mutually exclusive lists
TREES = ["spruce", "pine", "birch", "maple", "willow", "oak"]
MUSHROOMS = ["false morel", "chantarelle", "milkcap", "funnel chantarelle", "brittlegill", "black trumpet", "forest lamb"]
FLOWERS = ["lily", "bluebell", "violet", "daisy", "red clover", "dandelion", "yarrow", "anemone"]
OTHER = 0
TREE = 1
MUSHROOM = 2
FLOWER = 3
def print_in_alphabetical_order(list_of_strings):
list_of_strings.sort()
for i in list_of_strings:
print(i)
def classify_species(species):
i = str(species)
if i in TREES:
return TREE
elif i in MUSHROOMS:
return MUSHROOM
elif i in FLOWERS:
return FLOWER
else:
return OTHER
def main():
species = []
lajike = str(input("Enter the species of the items you found in the forest. Stop with empty line.\n"))
while lajike:
species.append(lajike)
lajike = str(input())
end = "\n"
print("Your finds in alphabetical order:")
print_in_alphabetical_order(species)
trees = []
mushrooms = []
flowers = []
other = []
“classify_species”功能应该可以正常工作。问题是,如何将 [species] 列表中的项目添加到主函数中的其他列表中?应该使用“classify_species”函数添加它们。我认为它必须使用 for-command 完成,但我不知道为什么。非常感谢您的帮助!
【问题讨论】:
-
欢迎来到Stack Overflow!请尝试将您问题中的代码进一步简化为minimal reproducible example。如果仍然与手头的问题相关,还请准确说明您想要实现的目标,例如,您只想计算标本(按物种类别)还是存储实际发生的物种?即,结果应该是“3 棵树,5 只蘑菇”还是“2 棵橡树,1 只桦树,5 只森林羔羊”?还尝试展示您尝试过的内容并解释它是如何失败的(您是否收到错误消息,代码的结果或其他行为是否超出预期等)。另请参阅 How to Ask 中的 help center。