python数组中怎样删除符合条件的元素

如题所述

使用filter来实现,以python3为例,如果删除列表中的所有0,则可使用下面代码实现:

a = [1,2,0,3,4,0,5,0,6]
b = filter(lambda x: x != 0, a)
list(b)

效果如下:

注:如果使用python2则直接输出b即可,在python3中filter返回结果为可迭代的对象,需使用list转换成列表。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-02-21

用filter函数可以方便地完成。

实例:删除数组中所有的字符串'a'

str = ['a', 'b','c', 'd']
def fun1(s): return s if s != 'a' else None
ret = filter(fun1, str)
print ret
## ['b', 'c', 'd']

摘自:

http://www.cnblogs.com/fangshenghui/p/3445469.html

本回答被提问者采纳
第2个回答  2016-02-21
相似回答