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

前端 未结 2 887
不知归路
不知归路 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 ]
    

提交回复
热议问题