我必须从数组中删除所有特定值(如果有的话),所以我写:
while value_to_remove in my_array:
my_array.remove(value_to_remove)
有没有更多的pythonic方法可以通过一个命令来做到这一点?
我必须从数组中删除所有特定值(如果有的话),所以我写:
while value_to_remove in my_array:
my_array.remove(value_to_remove)
有没有更多的pythonic方法可以通过一个命令来做到这一点?
你可以试试:
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']
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']
import itertools
my_array = list(itertools.ifilter(lambda x: x != value_to_remove, my_array))
不要错过有一个非常有效的方法如下:
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']