编写一个 Python 程序,使用 sort() 函数、reverse() 函数和带实际示例的 for 循环,在一系列项目中查找第二大的数字。
Python 程序使用 sort 查找列表中的第二大数字
这个 Python 程序允许用户输入长度。接下来,我们使用 For 循环将数字添加到列表中。sort 函数将列表元素按升序排序。接下来,我们使用索引位置在列表中打印倒数第二个元素。
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
NumList.sort()
print("The Largest Element in this List is : ", NumList[Number - 2])

Python 程序使用 reverse 函数查找列表中的第二大数字
此程序中的 sort() 函数将按升序对元素进行排序。接下来,我们使用reverse 函数来反转项目。最后,我们使用索引位置 1 打印列表中的第二个元素。如果你想要最大的,请使用索引位置 0。
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
NumList.sort()
NumList.reverse()
print("The Second Largest Element in this List is : ", NumList[1])

Python 程序使用 for 循环查找列表中的第二大数字
在此程序中,我们不使用任何内置函数,例如sort或reverse函数。为此,我们使用For 循环。
NumList = []
Number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
first = second = NumList[0]
for j in range(1, Number):
if(NumList[j] > first):
second = first
first = NumList[j]
elif(NumList[j] > second and NumList[j] < first):
second = NumList[j]
print("The Largest Element in this List is : ", first)
print("The Second Largest Element in this List is : ", second)

从上面的截图可以看出,用户插入的值是 NumList[4] = {55, 57, 22, 3}
first = second = NumList[0] = 55
第一次迭代 – for 1 in range(1, 4) – 条件为真。因此,它执行循环中的If 语句,直到条件失败。
if(NumList[j] > first) 在 for 循环中为 True,因为 (57 > 55)
second = first = 55
first = NumList[1] = 57
第二次迭代:for 2 in range(1, 4) – 条件为真。
If (NumList[2] > first) = (22 > 57) – 条件为 False。因此,它进入一个elif 语句
elif(NumList[2] > second and NumList[2] < first)
elif(22 > 55 and 22 < 57) – 条件为 False
第三次迭代:for 3 in range(1, 4) – 条件为真。
If (3 > 57) – 条件为 False
elif(3 > 55 and 3 < 57) – 条件为 False
第四次迭代:for 4 in range(1, 4) – 条件为 False。因此,它退出循环。