我只想检查一个numpy数组是否包含一个快速类似于包含列表的单个数字。有简洁的方法吗?
a = np.array(9,2,7,0)
a.contains(0) == true
答案 0 :(得分:8)
您可以使用var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
console.log(d.days(), d.hours(), d.minutes(), d.seconds());
。即
0 in a
答案 1 :(得分:3)
如果a是一个numpy数组:
a = np.array([1, 2])
然后使用:
1 in a
返回true,而:
0 in a
返回false
答案 2 :(得分:2)
我在python 3.7中定时了一些方法来做到这一点:
import numpy as np
rnd = np.random.RandomState(42)
one_d = rnd.randint(100, size=10000)
n_d = rnd.randint(100, size=(10000, 10000))
searched = 42
# One dimension
%timeit if np.isin(one_d, searched, assume_unique=True).any(): pass
%timeit if np.in1d(one_d, searched, assume_unique=True).any(): pass
%timeit if searched in one_d: pass
%timeit if one_d[np.searchsorted(one_d, searched)] == searched: pass
%timeit if np.count_nonzero(one_d == searched): pass
print("------------------------------------------------------------------")
# N dimensions
%timeit if np.isin(n_d, searched, assume_unique=True).any(): pass
%timeit if np.in1d(n_d, searched, assume_unique=True).any(): pass
%timeit if searched in n_d: pass
%timeit if np.count_nonzero(n_d == searched): pass
>>> 42.8 µs ± 79.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> 38.6 µs ± 76.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> 16.4 µs ± 57.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> 4.7 µs ± 62.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> 12.1 µs ± 69.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> ------------------------------------------------------------------
>>> 239 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> 241 ms ± 1.17 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> 156 ms ± 2.78 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> 163 ms ± 527 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
一维数组最快的是上面np.searchsorted
提出的数组,但是它不能用于ndarray。另外,np.count_nonzero
最快,但并不比pythonic in
快,因此我建议使用in
。
答案 3 :(得分:-1)
x = 0
if x in a:
print 'find'