2

Consider the array a= [1, 2, 3, 1, 2, 3]. Now suppose I want to remove all the 2s in this array in python. So I apply a.remove(2). However the result which comes out is [1, 3, 1, 2, 3], i.e the only first 2 is removed. How can I remove all the 2s which appear in an array? In general, given an array and an element p, how can I remove all the elements of the array which are equal to p?

Edit:- I think I should mention this, this question has been inspired from a Brilliant computer science problem.

4

2 回答 2

4

使用列表推导构建替换列表,其中所有元素都不等于p

a = [i for i in a if i != p]

请注意,在 Python 中,数据类型称为 a list,而不是数组。

于 2013-07-22T11:17:53.960 回答
3

您可以使用filter().

>>> a= [1, 2, 3, 1, 2, 3]
>>> filter(lambda x: x != 2, a)
[1, 3, 1, 3]

在一个函数中:

>>> def removeAll(inList, num):
        return filter(lambda elem: elem != num, inList)

>>> removeAll(a, 2)
[1, 3, 1, 3]
于 2013-07-22T11:19:11.090 回答