如何在Python中将一个数组的所有元素减去另一个数组的所有元素?
我需要从一个数组x1中的每个数字,减去另一个数组x2中的所有数字,然后检查结果的绝对值是否小于0.01。如果是这样的话,就把x1的这个数字放到一个新的数组里。接着,我需要对x1数组里的每个元素都重复这个过程。
这样做会需要进行250亿次计算,因为这两个数组都很长(一个有50000个元素,另一个有500000个元素),所以我希望能减少处理的工作量。
谢谢!
b = np.zeros(len(a), 1) #a is a list of numbers 48555 elements long
b[:,0] = a[:,0]
e = np.zeros(len(d), 1) #d is a list of numbers 531261 elements long
e[:,0] = d[:,0]
h = np.zeros(len(len(a)*len(d),1) #h needs to be an array of length a*d
for i in e, j in b,
if abs(i-j)<=0.01,
h.append(i)
print h
我之前没怎么用过代码,所以在用Python的时候还在犯一些比较基础的错误。
1 个回答
0
x1 = np.array([5, 8, 3, 4, 5, 6])
x2 = np.array([ 0, 6, 3, 4, 2, 7])
print all(abs(np.subtract(x2 ,x1[1]) < .01))
True
print all(abs(np.subtract(x2 ,x1[0]) < .01))
False
for ele in x1:
if any(abs(x - ele) > .01 for x in x2 ):
continue
else: add your array
你可以遍历 x1 的所有值,一旦发现有哪个值大于 0.01,就可以立刻停止检查其他值,这样可以节省时间。