我要处理9个数组以查找所有可能的组合,因此结果数组的名称告诉我已组合了哪些数组。例如:
a1_a2 = array1 - array2
a1_a3 = array1 - array3
a1_a4 = array1 - array4
.
.
.
a9_a6 = array9 - array6
a9_a7 = array9 - array7
a9_a8 = array9 - array8
很明显,我可以对其进行硬编码,但是如何循环进行呢?
我想为此编写一个函数,例如:
def combineArrays(array1, array2):
result_name = name_of_array1 + '_' + name_of_array2 # How would I do this bit?
result = array1 - array2
return result
for firstArray in arrays:
for secondArray in reversed(arrays): # to go backwards through the list of arrays
combineArrays(firstArray, secondArray)
例如,以下数组:
array1 = [1,2,nan,4,5]
array2 = [5,4,3,2,1]
array3 = [2,4,6,8,10]
应产生输出
a1_a2 = [-4,-2,nan,2,4]
a1_a3 = [-2,-4,nan,-8,-10]
a2_a1 = [4,2,nan,-2,-4]
a2_a3 = [2,-2,-6,-10,-14]
a3_a2 = [-2,2,6,10,14]
a3_a1 = [2,4,nan,8,10]
因此,对每种可能的数组组合进行逐元素减法。
自从我使用numpy
以来,是否甚至还有线性代数类型的方法?以及如何让程序为我命名数组?
This question似乎在问类似的问题,但我不明白答案。
答案 0 :(得分:0)
这是可以与任何功能一起使用的通用代码:您可能会通过它来理解,但它确实可以满足您的要求:
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
def choose(n,m):
if n < m:
raise ValueError("n is less than m!")
if m < 0:
raise ValueError("m cannot be negative!!")
else:
return int(factorial(n)/factorial(m)/factorial(n-m))
def combn(x, m, FUN = None):
import numpy as np
if not isinstance(m,int):
raise ValueError("m must be a single integer")
if isinstance(x, int) and x > 0:
x = np.arange(1, x+1)
n, x, e, h, a, nofun = len(x), np.array(x), 0, m, np.arange(1,m+1), FUN==None
if not nofun and not callable(FUN):
raise TypeError("'FUN' must be a function or None")
if (nofun):r = x[a-1]
else: r = FUN(x[a-1])
out = [None] * choose(n, m)
out[0] = r
if m > 0:
i = 2
nmmp1 = n - m + 1
while a[0] != nmmp1:
if e < n - h:
h, e, j = 1, a[m-1], 1
else:
e = a[m - h-1]
h += 1
j = np.arange(1,h+1)
a[m - h + j-1] = e + j
if (nofun): r = x[a-1]
else: r = FUN(x[a-1])
out[i-1] = r
i += 1
return out
您可以将其保存以供将来使用:。现在,在此之后,您可以进行所需的任何组合:
combn(4,3)
Out[854]: [array([1, 2, 3]), array([1, 2, 4]), array([1, 3, 4]), array([2, 3, 4])]
combn([1,2,3,4],3)
Out[855]: [array([1, 2, 3]), array([1, 2, 4]), array([1, 3, 4]), array([2, 3, 4])]
combn([1,2,3,4],3,sum)
Out[856]: [6, 7, 8, 9]
您可以这样做:
array1 = [1,2,np.nan,4,5]
array2 = [5,4,3,2,1]
array3 = [2,4,6,8,10]
combn([array1,array2,array3],2,lambda x: x[0]-x[1])
Out[859]:
[array([-4., -2., nan, 2., 4.]),
array([-1., -2., nan, -4., -5.]),
array([ 3., 0., -3., -6., -9.])]
现在使用lambda x:x[1]-x[0]
运行相同的代码,从而为您提供所需的所有组合