对没有双精度的数组求和

问题描述 投票:0回答:2

我想知道如果我按照下面的方式生成了3个数组,我怎样才能将所有3个数组中的所有数字相加,而不需要对每个数组中出现的数字进行求和。

(我只想将 10 添加一次,但我无法添加数组 X_1 和 X_2,因为它们都有 10 和 20,我只想将这些数字添加一次。)

也许这可以通过从 X_1、X_2 和 X_3 中创建一个新数组(省略双精度)来完成?

 def get_divisible_by_n(arr, n):
    return arr[arr%n == 0]
x = np.arange(1,21)

X_1=get_divisible_by_n(x, 2)
#we get array([ 2,  4,  6,  8, 10, 12, 14, 16, 18, 20])

X_2=get_divisible_by_n(x, 5)
#we get array([ 5, 10, 15, 20])
    
X_3=get_divisible_by_n(x, 3)
#we get array([3, 6, 9, 12, 15, 18]) 
python arrays function sum double
2个回答
1
投票

又是我! 这是我使用 numpy 的解决方案,因为这次我有更多时间:

import numpy as np

arr = np.arange(1,21)

divisible_by = lambda x: arr[np.where(arr % x == 0)]
n_2 = divisible_by(2)
n_3 = divisible_by(3)
n_5 = divisible_by(5)
what_u_want = np.unique( np.concatenate((n_2, n_3, n_5)) )
# [ 2,  3,  4,  5,  6,  8,  9, 10, 12, 14, 15, 16, 18, 20]

1
投票

效率不高,也不使用 numpy,但这是一种解决方案:

def get_divisible_by_n(arr, n):
    return [i for i in arr if i % n == 0]
   

x = [i for i in range(21)]

X_1 = get_divisible_by_n(x, 2)
X_2 = get_divisible_by_n(x, 5)
X_3 = get_divisible_by_n(x, 3)
X_all = X_1+X_2+X_3
y = set(X_all)
print(sum(y)) # 142
© www.soinside.com 2019 - 2024. All rights reserved.