递归函数可将任何函数应用于任意长度的N个数组,以形成一个N个锯齿状的多维数组 [英] Recursive function to apply any function to N arrays of any length to form one jagged multidimensional array of N dimensions
问题描述
给出N个输入数组,所有 any 个长度,我希望能够将一个函数应用于每个组合的 all 个组合每个数组.
Given N input arrays, all of any length, I would like to be able to apply a function to all combinations of every combination of each arrays.
例如:
给出输入数组:
[1、2][3,4,5][6,7,8,9]
还有一个返回N个元素乘积的函数
And a function which returns the product of N elements
我希望能够将功能应用于这些元素的每种组合.在这种情况下,它会产生一个三维数组,长度分别为2、3和4.
I would like to be able to apply a function to every combination of these elements. In this case it results in a 3 dimensional array, of lengths 2, 3, and 4 respectively.
结果数组如下:
[
[
[18, 21, 24, 27],
[24, 28, 32, 36],
[30, 35, 40, 45]
],
[
[36, 42, 48, 54],
[48, 56, 64, 72],
[60, 70, 80, 90]
]
]
推荐答案
使用np.frompyfunc创建所需函数的ufunc的另一种方法.这对n个参数使用ufuncs .outer方法n-1次.
An alternative approach using np.frompyfunc to create a ufunc of the required function. This is the applied with the ufuncs .outer method n-1 times for the n arguments.
import numpy as np
def testfunc( a, b):
return a*(a+b) + b*b
def apply_func( func, *args, dtype = np.float ):
""" Apply func sequentially to the args
"""
u_func = np.frompyfunc( func, 2, 1) # Create a ufunc from func
result = np.array(args[0])
for vec in args[1:]:
result = u_func.outer( result, vec ) # apply the outer method of the ufunc
# This returns arrays of object type.
return np.array(result, dtype = dtype) # Convert to type and return the result
apply_func(lambda x,y: x*y, [1,2], [3,4,5],[6,7,8,9] )
# array([[[18., 21., 24., 27.],
# [24., 28., 32., 36.],
# [30., 35., 40., 45.]],
# [[36., 42., 48., 54.],
# [48., 56., 64., 72.],
# [60., 70., 80., 90.]]])
apply_func( testfunc, [1,2], [3,4,5],[6,7,8,9])
# array([[[ 283., 309., 337., 367.],
# [ 603., 637., 673., 711.],
# [1183., 1227., 1273., 1321.]],
# [[ 511., 543., 577., 613.],
# [ 988., 1029., 1072., 1117.],
# [1791., 1843., 1897., 1953.]]])
这篇关于递归函数可将任何函数应用于任意长度的N个数组,以形成一个N个锯齿状的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!