Python 我创建的函数赢得了';t不接受数组作为参数之一
我写了一个函数,它有两个参数,一个用于无量纲,另一个用于无模拟。该函数完全执行所需操作(计算单位超球体的体积),但是,当我希望在一系列维度上绘制该函数时,它会返回一个错误:“list”对象不能解释为整数 我的职能是:Python 我创建的函数赢得了';t不接受数组作为参数之一,python,Python,我写了一个函数,它有两个参数,一个用于无量纲,另一个用于无模拟。该函数完全执行所需操作(计算单位超球体的体积),但是,当我希望在一系列维度上绘制该函数时,它会返回一个错误:“list”对象不能解释为整数 我的职能是: def hvolume(ndim, nsim): ob = [np.random.uniform(0.0,1.0,(nsim, ndim))] ob = np.concatenate(ob) i = 0 res = [] while i &
def hvolume(ndim, nsim):
ob = [np.random.uniform(0.0,1.0,(nsim, ndim))]
ob = np.concatenate(ob)
i = 0
res = []
while i <= nsim-1:
arr = np.sqrt(np.sum(np.square(ob[i])))
i += 1
res.append(arr)
N = nsim
n = ndim
M = len([i for i in res if i <= 1])
return ((2**n)*M/N)
def hvolume(ndim、nsim):
ob=[np.随机.均匀(0.0,1.0,(nsim,ndim))]
ob=np.连接(ob)
i=0
res=[]
在这种情况下,我使用的一种模式是以一个块开始函数,以处理迭代器的情况。举个例子
from collections import Iterator
def hvolume(ndim, nsim):
outputs = []
if isinstance(ndim, Iterator):
for ndim_arg in ndim:
outputs.append(hvolume(ndim_arg, nsim))
if isinstance(nsim, Iterator):
for nsim_arg in nsim:
outputs.append(hvolume(ndim, nsim_arg))
if len(outputs) == 0: # neither above is an Iterator
# ... the rest of the function but it appends to outputs
return outputs
如果您只是尝试函数中的第一行
ob = [np.random.uniform(0.0,1.0,(nsim, ndim))]
将列表作为变量之一,如下所示
[np.random.uniform(0.0,1.0,([1,2], 2))]
您将得到以下错误:
TypeError: 'list' object cannot be interpreted as an integer
这是因为uniform命令要求它查找整数,而不是列表。如果你想处理列表,你需要做一个for循环 检查方法“hvolume”的输入参数,似乎您给出了一个nsim或ndim列表,两者都应该是整数值。这使得制服抛出一个TypeError异常。错误在第4行。请发布完整的错误回溯。什么是modulenp
?@SRTHellKitty posted.@user803422 numpy作为np导入。我理解。我将再次尝试重写它!谢谢
TypeError: 'list' object cannot be interpreted as an integer