如何从矢量中删除数字?

如何从矢量中删除数字?

问题描述:

我有这个载体如何从矢量中删除数字?

v = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20) 

我想删除的2倍数和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) 
Mul3 = np.arange(1,21,3) 
Mul2 = np.arange(1,21,2) 
V1 = V [-mul2] 
V2 = V1 [-mul3] 

既然你使用NumPy的已经可以使用boolean array indexing删除的23倍数:

>>> 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)产生boolean值面具其中2倍数False和其他一切True,同样的(arr % 3 != 0)作品的3倍数。这两个面具使用&(和)合并,然后用作您的面具arr

我想通过你指的是你设置与()元组vector

您可以使用list comprehension有两个条件下,利用modulo oprerator你可以here读了起来:

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

返回

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

这将返回一个标准的Python列表;如果你想要np数组或者......只是更新你的问题。

您可以使用模2和3的结果直接在列表理解中进行过滤。这使得项目,其mod 2mod 3值给出比其他数字的falsy 0:

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

你可以使它更详细的,如果上面没有通过使条件语句明确地测试非零结果不够直观:

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