简体   繁体   English

在 python 中基于列表理解的条件跳过元素

[英]Skip elements on a condition based in a list comprehension in python

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 another list.对于列表中小于零 (0) 的数字,我想跳过这些数字并形成另一个列表。

Example:-例子:-

List = [9,4,7,0,1]

This is a kind of doubt I have, not sure If we can achieve.这是我的一种疑惑,不确定是否可以实现。 If it's possible to achieve, can anyone please post here.如果有可能实现,任何人都可以在这里发帖。

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() :使用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:在 Python 3 中, filter()返回一个filter对象(不是list ),要将其转换为列表,您可以执行以下操作:

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

First use lower case for variable names, second don't use list because it reserved name.首先对变量名称使用小写,其次不要使用list因为它保留了名称。

Then just do an if inside the list comprehension然后在列表理解中做一个 if

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

I have tried this code here my_list = [i for i in init_list if i >= 0 ] but i had modified it to fit to my use and i would like to say that it can be used like this:我在这里尝试过这段代码 my_list = [i for i in init_list if i >= 0 ] 但我修改了它以适合我的使用,我想说它可以像这样使用:

for i in [x for x in range(10) if != 3] 

I used it here to make the program skip a iteration.我在这里使用它来使程序跳过迭代。

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

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