[英]Function over each value in Python Array (without using def)
The input array is x with dimensions (1 x 3) and the output array is 3 x 3 (column of input x column of input).输入数组为 x,尺寸为 (1 x 3),output 数组为 3 x 3(输入列 x 输入列)。 The output array's diagonals are the values^2.
output 阵列的对角线是值^2。 If row,= column.
如果行,= 列。 then the formula is x(row)+x(col) for each value.
那么公式是每个值的 x(row)+x(col)。 Currently for 1 x 3 but should assume a variety of dimensions as input.
目前为 1 x 3,但应假定各种尺寸作为输入。 Cannot use 'def', The current code does not work?
不能使用'def',当前代码不起作用? what would you recommend?
你会推荐什么?
x = np.array([[0, 5, 10]])
output array formulas =
[[i^2, x(row)+x(col), x(row)+x(col)]
[x(row)+x(col), i^2, x(row)+x(col)]
[x(row)+x(col), x(row)+x(col), i^2]]
# where row and column refer to the output matrix row, column. For example, the value in (1,2) is x(1)+x(2)= 5
ideal output =
[[0 5 10]
[5 25 15]
[10 15 100]]
Code Attempted:尝试的代码:
x = np.array([[0, 5, 10]])
r, c = np.shape(x)
results = np.zeros((c, c))
g[range(c), range(c)] = x**2
for i in x:
for j in i:
results[i,j] = x[i]+x[j]
Learn to use numpy methods and broadcasting:学习使用numpy方法和广播:
>>> x
array([[ 0, 5, 10]])
>>> x.T
array([[ 0],
[ 5],
[10]])
>>> x.T + x
array([[ 0, 5, 10],
[ 5, 10, 15],
[10, 15, 20]])
>>> result = x.T + x
>>> result
array([[ 0, 5, 10],
[ 5, 10, 15],
[10, 15, 20]])
Then this handy built-in:然后这个方便的内置:
>>> np.fill_diagonal(result, x**2)
>>> result
array([[ 0, 5, 10],
[ 5, 25, 15],
[ 10, 15, 100]])
Can replace the results[range(c), range(c)] = x**2
可以替换
results[range(c), range(c)] = x**2
Here is how you can do it without using numpy:以下是不使用 numpy 的方法:
x = [[0,5,10] for i in range(3)]
output = [[x[i][j]**2 if i == j else x[i][j] for j,b in enumerate(a)] for i,a in enumerate(x)]
print(output)
output: output:
[[0, 5, 10], [0, 25, 10], [0, 5, 100]]
Try this:尝试这个:
x.repeat(x.shape[1], axis=0)
x = x+x.T
x[np.arange(len(x)),np.arange(len(x))] = (np.diag(x)/2)**2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.