Skip elements on a condition based in a list comprehension in python

前端 未结 2 865
不知归路
不知归路 2020-12-31 06:46

I have a list List:

List = [-2,9,4,-6,7,0,1,-4]

For numbers less than zero (0) in the list , I would like to skip those numbers and form an

相关标签:
2条回答
  • 2020-12-31 07:02

    First use lower case for variable names, second don't use list because it reserved name.

    Then just do an if inside the list comprehension

    my_list = [i for i in init_list if i >= 0 ]
    
    0 讨论(0)
  • 2020-12-31 07:06

    You have many options to achieve that. With a list comprehension you can do:

    my_list = [i for i in my_list if i>=0]
    

    With filter():

    my_list = filter(lambda i: i>=0, my_list)
    

    Note:

    In Python 3, filter() returns a filter object (not list), to convert it to a list, you can do:

    my_list = list(filter(lambda i: i>=0, my_list))
    
    0 讨论(0)
提交回复
热议问题