如何从向量中删除数字? [英] How to delete numbers from a vector?
本文介绍了如何从向量中删除数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个向量
v = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20)
我想删除2和3的倍数.我该怎么做?
I want to remove the multiples of 2 and 3. How would I do this?
我试图这样做,但是我没有用:
I tried to do this but I doesn't work:
import numpy as np
V = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20)
Mul3 = np.arange(1,21,3)
Mul2 = np.arange(1,21,2)
V1 = V [-mul2]
V2 = V1 [-mul3]
推荐答案
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])
(arr % 2 != 0)
创建一个布尔掩码,其中2
的倍数是False
,其他所有元素True
以及(arr % 3 != 0)
都适用于3
的倍数.这两个遮罩使用&
(和)组合在一起,然后用作arr
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
这篇关于如何从向量中删除数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文