Remove all specific value from array
我必须从数组中删除所有特定的值(如果有的话),所以我写:
1 2 | while value_to_remove in my_array: my_array.remove(value_to_remove) |
通过一个命令,是否有更多的Python方法来完成这个任务?
您可以尝试:
例子:
1 2 3 | >>> my_array = ["abc","def","xyz","abc","pop","abc"] >>> filter (lambda a: a !="abc", my_array) ['def', 'xyz', 'pop'] |
1 2 3 4 5 6 7 | 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'] |
号
使用
1 2 3 | import itertools my_array = list(itertools.ifilter(lambda x: x != value_to_remove, my_array)) |
不要错过有一个非常有效的方法,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 2 3 4 5 6 7 8 9 | >>> [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'] |