从数组中删除所有特定值

时间:2012-10-23 14:13:13

标签: python

我必须从数组中删除所有特定值(如果有的话),所以我写道:

while value_to_remove in my_array:
    my_array.remove(value_to_remove)

通过一个命令有更多的pythonic方法吗?

4 个答案:

答案 0 :(得分:8)

您可以尝试:

filter (lambda a: a != value_to_remove, my_array)

示例:

>>> my_array = ["abc", "def", "xyz", "abc", "pop", "abc"]
>>> filter (lambda a: a != "abc", my_array)
['def', 'xyz', 'pop']

答案 1 :(得分:3)

clean_array = [element for element in my_array if value_to_remove != element]

my_array = ('a','b','a','c')
value_to_remove = 'a'
>>> clean_array = [element for element in my_array if value_to_remove != element]
>>> clean_array
['b', 'c']

答案 2 :(得分:2)

使用itertools.ifilter

import itertools

my_array = list(itertools.ifilter(lambda x: x != value_to_remove, my_array))

答案 3 :(得分:1)

不要错过以下非常有效的方式:

import numpy as Numpy

a = Numpy.array([1,7,3,4,4,6,3,8,7,0,8])
b = Numpy.array(['1','7','3','4','4','6','3','8','7','0','8'])
c = Numpy.array([0.1,9.8,-0.4,0.0,9.8,13.7])
d = Numpy.array(['one','three','five','four','three'])

print a
print a[a!=3]

print b
print b[b!='3']

print c
print c[c!=9.8]

print d
print d[d!='three']

你得到:

>>> 
[1 7 3 4 4 6 3 8 7 0 8]
[1 7 4 4 6 8 7 0 8]
['1' '7' '3' '4' '4' '6' '3' '8' '7' '0' '8']
['1' '7' '4' '4' '6' '8' '7' '0' '8']
[  0.1   9.8  -0.4   0.    9.8  13.7]
[  0.1  -0.4   0.   13.7]
['one' 'three' 'five' 'four' 'three']
['one' 'five' 'four']