在基于python中的列表理解的条件下跳过元素 [英] Skip elements on a condition based in a list comprehension in python

查看:591
本文介绍了在基于python中的列表理解的条件下跳过元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表:

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

对于列表中小于零(0)的数字,我想跳过这些数字并形成另一个列表.

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

示例:-

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]

使用 filter() :

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

注意:

在Python 3中,filter()返回一个filter对象(不是list),可以将其转换为列表,您可以执行以下操作:

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))

这篇关于在基于python中的列表理解的条件下跳过元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆