简体   繁体   English

如何从 python 中的列表中只获取负数

[英]How to get only negative numbers from a list in python

I'm trying to make def get_neg(): so that get_neg(lst) returns "-1, -2, -3" when lst = [-1, -2, -3, 4, 5, 6].我正在尝试制作 def get_neg(): 以便 get_neg(lst) 在 lst = [-1, -2, -3, 4, 5, 6] 时返回“-1, -2, -3”。 I tried this code below, but I don't know how to get the result in 1 line.我在下面尝试了这段代码,但我不知道如何在 1 行中获得结果。

def get_neg():
    for n in lst:
        if n < 0:
            print(str(n) + ',')
        else:
            pass

This way I get each numbers in a different row and a comma at the end.通过这种方式,我将每个数字放在不同的行中,并在末尾加上一个逗号。 It has to be programmed with basic commands它必须使用基本命令进行编程

You can use list comprehensions (Do not forget to give lst as an argument to the get_neg function):您可以使用列表理解(不要忘记将lst作为get_neg函数的参数):

def get_neg(lst):
    return [x for x in lst if x < 0]

Example例子

get_neg([-1,-2,4,5]) # [-1, -2]
get_neg([-15,-22,-4, 5, 0]) # [-15, -22, -4]

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

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