简体   繁体   English

如何转换为浮动列表?

[英]How to convert a list in a float?

My code has the following error: float () argument must be a string or a number, not 'list'. 我的代码有以下错误:float()参数必须是字符串或数字,而不是'list'。

I know that my ww function is a list of values, but I do not know how to convert it to float, since ww is a function. 我知道我的ww函数是一个值列表,但是我不知道如何将其转换为浮点数,因为ww是一个函数。 I tried list comprehension, following the question in: 我按照以下问题尝试了列表理解:

TypeError: float() argument must be a string or a number, not 'list' python TypeError:float()参数必须是字符串或数字,而不是'list'python

But it didn't work. 但这没有用。

def func(n):
    return 2/(n+1)

def ww(n):
    return [-1 + i*func(n) for i in range(0,n+1)] 

def g(x,y):
    return x**2 + y

This g(x,y) is actually spherical harmonics, but I put this for simplicity. 这个g(x,y)实际上是球谐函数,但为简单起见,我将其放置。

def integral(n):
    return [np.pi*func(n)*(1 + math.cos(np.pi*(-1 + i*func(n))))*g(np.pi*i,ww(n)) for i in range(0,n+1)]   

Your ww function returns a list of floats, which are then passed into g() . 您的ww函数返回一个浮点列表,然后将其传递到g() The calculation fails because you cannot add a list to a number. 计算失败,因为您无法向数字添加list

It is not possible to "convert a list of floats to a float" without performing some sort of operation on the numbers — eg "add", "subtract", "multiply". 如果不对数字执行某种操作,例如“加”,“减”,“乘”,就不可能将“浮点列表转换为浮点”。

However, you can convert the list to an numpy array, which can be operated on as a whole. 但是,您可以将列表转换为numpy数组,该数组可以作为一个整体进行操作。 Multiplying an array of numbers by a single number multiplies each value, returning the result. 将数字数组乘以一个数字将每个值相乘,返回结果。

For example: 例如:

>>> a = np.array([1.0,2.0,3.0])
>>> b = 2
>>> b ** 2 + a
array([5.0, 6.0, 7.0])

If you wrap the return value of ww to convert to a numpy array, the subsequent calculation in g() should work. 如果包装ww的返回值以转换为numpy数组,则g()的后续计算应该有效。

def ww(n):
    return np.array([-1 + i*func(n) for i in range(0,n+1)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM