Python循环异常:查找列表最值时提前停止比较的问题排查
Python列表最值查找循环错误修复
问题现象
测试输入数字23、34、68、3、566、2、1后,代码输出结果如下:
current list > ['23', '34', '68', '3', '566', '2', '1'] the smallest number is > 1 largest number is > 68
实际最大值应为566,但输出错误,最小值结果正确。
问题代码
largest = None smallest = None a = [] while True: num = input("Enter a number: ") if num == "done": break try: FailureCond = int(num) except ValueError: print("that's not a number") continue a.append(num) continue for i in range(len(a)): if smallest is None: smallest = a[i] largest = a[i] if a[i] < smallest: smallest = a[i] if a[i] > largest: largest = a[i] print("current list >",a) print("the smallest number is >",smallest) print("largest number is >",largest)
错误原因
列表a中存储的是字符串类型的数字,而非整数类型。字符串比较是按单个字符的ASCII码值逐位对比:
- '566'的第一个字符是'5'(ASCII码53),'68'的第一个字符是'6'(ASCII码54),所以
'566' > '68'的结果为False,导致最大值无法更新为566。 - 最小值正确是因为'1'的ASCII码比其他字符串的首字符都小。
修复方案
方案一:存储整数类型
将输入的字符串转换为整数后再存入列表,修改a.append(num)为a.append(int(num)):
largest = None smallest = None a = [] while True: num = input("Enter a number: ") if num == "done": break try: num_int = int(num) except ValueError: print("that's not a number") continue a.append(num_int) for i in range(len(a)): if smallest is None: smallest = a[i] largest = a[i] if a[i] < smallest: smallest = a[i] if a[i] > largest: largest = a[i] print("current list >",a) print("the smallest number is >",smallest) print("largest number is >",largest)
方案二:比较时转换为整数
在循环比较环节,将列表元素转换为整数后再进行判断:
largest = None smallest = None a = [] while True: num = input("Enter a number: ") if num == "done": break try: FailureCond = int(num) except ValueError: print("that's not a number") continue a.append(num) for i in range(len(a)): current_num = int(a[i]) if smallest is None: smallest = current_num largest = current_num if current_num < smallest: smallest = current_num if current_num > largest: largest = current_num print("current list >",a) print("the smallest number is >",smallest) print("largest number is >",largest)
内容的提问来源于stack exchange,提问作者Thanh bui dux
相关产品推荐
相关产品推荐

