如何使用不同于输入的哨兵值和按功能排序列表?



我正在学习初学者python,有一个问题我被困住了。

该问题涉及要求用户输入他们采摘的蘑菇的任何数量,输入重量,然后根据用户输入对它们进行排序。为此,需要一个列表和一个 while 循环来将输入附加到列表中。

目前,我正在尝试实现一个哨兵值,该值将在输入所有用户输入后停止 while 循环,但将哨兵设置为"STOP"与 int(( 通知冲突。

if __name__ == "__main__":
STOP = "stop"
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
total_list = []
while total_list != STOP:
total_list.append(mushroom)
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
print(total_list)

程序运行良好,直到进入"STOP",出现语法错误。

mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
ValueError: invalid literal for int() with base 10: 'STOP'

如您所见,哨兵值 STOP 与我的输入建议冲突,导致错误。

至于问题的第二部分,我需要按权重对值输入进行排序。如果一切都正确完成,我应该有一个包含所有值的列表。 我可以使用哪种代码对值进行排序? 我需要根据小 (<100(、中 (100-1000( 和大 (>1000( 对每个整数值进行排序,然后在语句中打印结果。 我对我需要在这里做什么有点一无所知。

谢谢,只是有点卡在一个地方。

您可以使用尝试将非整数转换为整数所产生的错误,通过 Python 中的tryexcept来发挥自己的优势。这是这方面的文档。

重写代码,您可以尝试以下操作:

if __name__ == "__main__":
STOP = "STOP"
total_list = []
while True:
try:
user_input = input("Enter a mushroom weight in grams, or STOP to end. ")
total_list.append(int(user_input))  
except ValueError:
if user_input.strip().upper()==STOP:
break
else:
print("Incorrect entry! '{}' is not an integer".format(user_input))     

然后,如果要对该列表进行排序并按类别进行排序,则可以考虑使用字典:

total_list.sort()       
di={'Small':[],'Medium':[],'Large':[]}
for e in total_list:
key='Small' if e<100 else 'Medium' if 100<=e<=1000 else 'Large'
di[key].append(e)
print(total_list, sum(total_list),di)

第一次崩溃是因为您尝试将"STOP"转换为整数。例如,如果你打开一个python解释器并输入int("STOP"(,你会得到同样的崩溃。解释器不知道如何将字符串"STOP"转换为整数。更好的方法可能是检查输入字符串是否可以使用 isdigit(( 或 try/except 转换为整数。

对于过滤,最简单的方法是在列表上使用列表推导。这样的事情应该有效:

if __name__ == "__main__":
mushroom = None
total_list = []
while mushroom != "STOP":
mushroom = input("Enter a mushroom weight in grams, or STOP to end. ")
if mushroom.isdigit():
total_list.append(int(mushroom))
sorted_total_list = sorted(total_list)
small_values = [mushroom for mushroom in total_list if mushroom < 100]
medium_values = [mushroom for mushroom in total_list if 100 <= mushroom <= 1000]
large_values = [mushroom for mushroom in total_list if mushroom > 1000]
print(sorted_total_list)
print(small_values)
print(medium_values)
print(large_values)

最新更新