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
提交
取消