我想要输出None而不是0

时间:2018-11-10 18:57:37

标签: python python-3.x

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 second
print(second_largest([2,2,2]))

如果没有第二大数字并且还有空列表,我想以None不输出0。

2 个答案:

答案 0 :(得分:2)

尝试将返回行更改为return second or None

答案 1 :(得分:0)

在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]))