如何基于条件将用户输入分类到列表?Python衣物程序求助
问题解决:衣物分类与筛选代码修正
你的代码核心问题在于输入循环里没有保存用户输入的数据,也没有将这些数据转化为Clothing实例加入衣物列表,另外还缺少根据当前温度和场合正式度筛选符合条件衣物的逻辑。下面是修正后的完整代码:
class Clothing: def __init__(self, fit: str, mintemp: int, maxtemp: int, formalitylvl: str): self.fit = fit self.mintemp = mintemp self.maxtemp = maxtemp self.formalitylvl = formalitylvl if __name__ == '__main__': listofclothes = [] # 初始化默认衣物 listofclothes.append(Clothing("coat", 0, 60, "yes")) listofclothes.append(Clothing("dress", 0, 100, "yes")) listofclothes.append(Clothing("T-shirt", 40, 100, "no")) listofclothes.append(Clothing("Hoodie", 0, 60, "no")) listofclothes.append(Clothing("jean shorts", 60, 100, "no")) # 让用户添加自定义衣物 catalog = int(input("请输入要添加的衣物数量: ")) for i in range(catalog): name = input("请输入衣物名称: ") min_temp = int(input("请输入该衣物适合的最低温度: ")) max_temp = int(input("请输入该衣物适合的最高温度: ")) formal = input("该衣物是否正式(输入yes/no): ").lower() # 统一转小写避免大小写问题 # 创建Clothing实例并加入列表 listofclothes.append(Clothing(name, min_temp, max_temp, formal)) # 获取当前温度和场合正式度 current_temp = int(input("请输入当前温度: ")) event_formality = input("请输入场合正式度(输入yes/no): ").lower() # 筛选符合条件的衣物 suitable_clothes = [] for item in listofclothes: # 判断温度是否在区间内,且正式度匹配 if item.mintemp <= current_temp <= item.maxtemp and item.formalitylvl == event_formality: suitable_clothes.append(item.fit) # 输出结果 if suitable_clothes: print("当前适合穿着的衣物:") for cloth in suitable_clothes: print(f"- {cloth}") else: print("没有找到符合条件的衣物")
关键修正点说明:
- 输入数据保存与实例创建:把用户输入的每一项都存到变量中,再用这些变量创建
Clothing对象,通过append加入衣物列表,解决了原代码无法将用户输入转化为衣物实例的问题。 - 统一输入格式:将正式度输入转为小写,避免用户输入"Yes"/"NO"等格式导致匹配失败的问题。
- 筛选逻辑实现:遍历衣物列表,同时判断温度是否在衣物的适用区间内,且正式度与场合要求匹配,最后收集并输出符合条件的衣物。
内容的提问来源于stack exchange,提问作者galapagos
相关产品推荐
相关产品推荐

