n=4
a1 = '-7 -7 -7 -7 -6'
a1=[int(arr_temp) for arr_temp in a1.strip().split(' ')]
print(a1)
largest = max(a1)
largest2 = 0
for i in range(0,len(a1)):
if ((a1[i]>largest2 or a1[i]<0) and largest2<largest and a1[i]!=largest):
largest2 = a1[i]
print(largest2)
答案 0 :(得分:1)
将maximum2设置为0只会使if语句变得复杂。将它设置为数组中的最小值,它会变得更清晰。
n=4
a1 = '-7 -7 -7 -7 -6'
a1=[int(arr_temp) for arr_temp in a1.strip().split(' ')]
print(a1)
largest = max(a1)
largest2 = min(a1)
for i in range(0,len(a1)):
if (a1[i] > largest2) and (a1[i] < largest):
largest2 = a1[i]
print(largest2)
请注意,如果数组很大,则对min的调用变得非常重要。在这种情况下,您可以将maximum2设置为可能的最小值(在该注释中,this链接可能有用)