def second_largest(numbers): first, second = 0,0 for n in numbers: if n > first: first, second = n, first elif first > n > second: second = n return secondprint(second_largest([2,2,2]))如果沒有第二大數字并且還有空列表,我想通過 None 而不是 0 輸出。
2 回答

梵蒂岡之花
TA貢獻1900條經驗 獲得超5個贊
在 return 語句中稍作調整就可以了。查看以下代碼:
def second_largest(numbers):
first, second = 0,0
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return None if second ==0 else second
print(second_largest([2,2,2]))
添加回答
舉報
0/150
提交
取消