如何在不使用Python中的循环的情况下在某些条件下制作数字的权力?
问题描述:
我想在python中计算这个简单的代码,给定一个矩阵根据它的条目修改它。如果(i, j)-th
条目大于或等于1
,则使其达到a
的功率,否则使其为1
。如何在不使用Python中的循环的情况下在某些条件下制作数字的权力?
import numpy
def restricted_power(k, n, d, a):
"""
:param d: a distance matrix
:param k, n: shape of d
:param a: a positive real number
:return: a modified distance matrix
"""
x = numpy.zeros((k,n))
for i in range(k):
for j in range(n):
if d[i, j] < 1:
x[i, j] = 1
else:
x[i, j] = d[i, j] ** a
return x
有没有一种方法来编写这个没有循环?
答
嗯,在某些时候不可能没有循环,但是你可以用numpy把循环推到C层。
>>> import numpy as np
>>> example = np.arange(9).reshape(3,3)/4.0
>>> example
array([[ 0. , 0.25, 0.5 ],
[ 0.75, 1. , 1.25],
[ 1.5 , 1.75, 2. ]])
>>> a = 2 # sample exponent
>>> np.where(example < 1, 1, example**a)
array([[ 1. , 1. , 1. ],
[ 1. , 1. , 1.5625],
[ 2.25 , 3.0625, 4. ]])
什么是x?为什么你想要解决这个没有循环? – Zorgmorduk