简体   繁体   English

如果列表中没有负数,Python如何打印0?

[英]Python how to print 0 if there are no negative numbers in a list?

I have to print the first negative number in a list, but if there are no negative numbers I have to return it as 0. I cannot for the life of me figure this out, I feel very dumb. 我必须打印列表中的第一个负数,但是如果没有负数,我必须将其返回为0。我一生无法弄清楚这一点,我感到非常傻。

def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number

Currently it works if there are negative numbers, but if there aren't, it'll return nothing. 目前,如果有负数,它可以工作,但是如果没有负数,它将不返回任何东西。 I can't seem to make it so it returns 0 instead of nothing 我似乎无法做到这一点,所以它返回0而不是什么

You can use this one-liner: 您可以使用这种单线:

num = next((x for x in numbers if x < 0), 0)

There's a little package on PyPI providing the first() function which might be more convenient: PyPI上有一个小包,它提供了first()函数,可能会更方便:

from first import first    
num = first(numbers, key=lambda x: x < 0, default=0)

Add return 0 outside of the for loop. for循环外添加return 0 The program arrives there only if it didn't find any negative number. 该程序仅在找不到任何负数时才到达那里。

def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number
    return 0

try this: 尝试这个:

def find_negative(list_numbers):
    first_index = 0
    for list_number in list_numbers:
        if list_number < 0:
            first_index = list_number
            break
    return first_index

Your code works fine if you do this to return the first negative number in the list but it doesn't mention any else thing to do if the condition is not met ie if there are no negative numbers. 如果您执行此操作以返回列表中的第一个负数,则您的代码可以正常工作,但如果不满足条件(即不存在负数),则它没有提及其他任何事情。 so you can use another variable which can be zero initially and will become equal to list_number if there is a negative number and remain zero only if there are no negative numbers in the list. 因此,您可以使用另一个变量,该变量最初可以为零,并且在存在负数的情况下将等于list_number,并且仅当列表中没有负数时才保持为零。

def find_negative(list_numbers): Number=0 for list_number in list_numbers: if list_number < 0: Number= list_number break return Number def find_negative(list_numbers):list = 0中list_number的number = 0:如果list_number <0:Number = list_number中断返回Number

In the above code, the loop will break once it encounters a negative number and will return the index of that number and if it doesn't come across a negative number, it will return a zero. 在上面的代码中,循环将在遇到负数时中断,并返回该数字的索引,如果未遇到负数,则将返回零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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