检查python代码中第二个最小的列表



我得到了这个练习:将未知数量的正整数作为输入。假设第一个数字总是比第二个数小,所有的数字都是唯一的输入至少包含三个整数。输出第二个最小的整数。我写了这段代码:

list=[10,12,1,3,2]
#find smallest number
if list[0]>list[1]:
smallest = list[1]
else:
smallest = list[0]
if smallest>list[2]:
smallest = list[2]
if smallest > list[3]:
smallest = list[3]
if smallest > list[4]:
smallest = list[4]
#remove smallest number from list
list.remove(smallest)
#find smallest number in new list
if list[0]>list[1]:
second_smallest = list[1]
else:
second_smallest = list[0]
if second_smallest > list[2]:
second_smallest = list[2]
if second_smallest > list[3]:
second_smallest = list[3]
print(second_smallest)

我能做些什么来简化它?谢谢!

您可以使用python的列表排序方法:

my_list = [10, 12, 1, 3, 2]
my_list.sort()
print(my_list[1])
numbers = ...
smallest = numbers[0]
second_smallest = numbers[1]
for index in range(2, len(numbers)):
number = numbers[index]
if number < smallest:
second_smallest = smallest
smallest = number
elif number < second_smallest:
second_smallest = number
print(second_smallest)

这个解决方案利用了前两个数字是有序的假设。当然,如果你能够使用python内置,你可以使用以下代码:

print(sorted(numbers)[1])

heapq中的nsmallest应该是您所需要的:

>>> lst = [2, 21, 20, 63, 53, 0, 38, 20, 11, 26]
>>> from heapq import nsmallest
>>> nsmallest(2, lst)[-1]
2

您可以先使用min函数获得列表中最小的数字。

num_list = [10, 12, 1, 3, 2]
min_num = min(num_list)

然后,通过过滤掉min_num来创建一个新列表,使filtered_list中最小的数字实际上是初始列表中第二小的值。

filtered_list = [n for n in num_list if n != min_num]
print(min(filtered_list))
my_list = [10, 12, 1, 3, 2]
my_list.sort()
print(my_list[1])

In Case In duplicate In list

my_list = [10, 12, 1, 1, 1, 1, 3, 2]
my_list.sort()
mylist = list(dict.fromkeys(my_list))
print(mylist[1])

相关内容

最新更新