以下是一种方法:

def find_second_smallest(numbers):
    smallest = float('inf')
    second_smallest = float('inf')
    for num in numbers:
        if num < smallest:
            second_smallest = smallest
            smallest = num
        elif smallest < num < second_smallest:
            second_smallest = num
    return second_smallest

这个函数接受一个数字列表作为参数,然后迭代列表中的每个数字。如果当前数字比当前最小值小,它就被设置为第二小的数字,并将当前最小值更新为它。如果当前数字在当前最小值和第二小的数字之间,它就被设置为第二小的数字。

使用示例:

>>> numbers = [5, 2, 8, 1, 9, 4, 3]
>>> find_second_smallest(numbers)
2
请用python写出:找到列表中第二小的数字

原文地址: https://www.cveoy.top/t/topic/bH62 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录