How to delete numbers from a vector?

和自甴很熟 提交于 2019-12-06 13:41:55

Given that you use NumPy already you can use boolean array indexing to remove the multiples of 2 and 3:

>>> import numpy as np
>>> v = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20)  # that's a tuple
>>> arr = np.array(v)  # convert the tuple to a numpy array
>>> arr[(arr % 2 != 0) & (arr % 3 != 0)]
array([ 1,  5,  7, 11, 13, 19])

The (arr % 2 != 0) creates a boolean mask where multiples of 2 are False and everything else True and likewise the (arr % 3 != 0) works for multiples of 3. These two masks are combined using & (and) and then used as mask for your arr

I assume by vector you refer to the tuple you set up with the ().

You can use a list comprehension with two conditions, using the modulo oprerator you can read up on here:

res = [i for i in v if not any([i % 2 == 0, i % 3 == 0])]

Returns

[1, 5, 7, 11, 13, 19]

This returns a standard Python list; if you want np arrays or sth, just update your question.

You could use the outcome of the modulos 2 and 3 directly for filtering in a list comprehension. This keeps items whose mod 2 and mod 3 values gives a number other than a falsy 0:

>>> [i for i in v if i%2 and i%3]
[1, 5, 7, 11, 13, 19]

You can make it more verbose if the above is not intuitive enough by making the conditionals explicitly test for non zero outcomes:

>>> [i for i in v if not i%2==0 and not i%3==0]
[1, 5, 7, 11, 13, 19]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!