如何从矢量中删除数字?

时间:2017-07-17 13:30:25

标签: python numpy vector indexing multiple-select

我有这个载体

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]

3 个答案:

答案 0 :(得分:7)

我假设if(controllofile) { write-host "Il file esiste, quindi il disco virtuale è correttamente montato nel server." write-host "Termino la procedura e non faccio altro." } 您引用了使用vector设置的元组。

您可以使用list comprehension两个条件,()使用您可以在here上阅读的modulo oprerator:

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

返回

  

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

这将返回一个标准的Python列表;如果您想要np数组或者某事,请更新您的问题。

答案 1 :(得分:4)

鉴于您已使用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)创建一个布尔值掩码,其中2的倍数为False,其他所有内容为True,同样(arr % 3 != 0)适用于{{1}的倍数}}。这两个掩码使用3(和)合并,然后用作&

的掩码

答案 2 :(得分:3)

您可以直接使用模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]