简体   繁体   中英

I want output None instead of 0

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

I want to output by None not 0 if there is no second largest number and also if there is empty list.

尝试更改返回行以return second or None

A little tweak in return statement will do. Check out the below code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM