'float' 对象没有属性 '__getitem__' Python 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25950113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:51:06  来源:igfitidea点击:

'float' object has no attribute '__getitem__' Python error

python

提问by Jonny

When I run the code

当我运行代码

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# Initial conditions

def f_func(eta,y_in):
    y_out = np.zeros(3)
    y_out[0] = y_in[1]
    y_out[1] = y_in[2]
    y_out[2] = -y_in[0]*y_in[2]/2
    return y_out

eta = np.linspace(0,8,100)
X0 = [0,0,0.33206]
X = odeint(f_func,X0,eta)

I get the error

我收到错误

 'float' object has no attribute '__getitem__'

When I run the following MATLAB program, everything works OK. The MATLAB function ode45 is equivalent to Pythons' odeint.

当我运行以下 MATLAB 程序时,一切正常。MATLAB 函数 ode45 等效于 Python 的 odeint。

main program:

主程序:

clear

global beta
beta = 1;

initial_value = [0,0,1.2322];
eta = linspace(0,4,100)
[x_out, y_out] = ode45(@falkner_skan,eta,initial_value);

plot(x_out,y_out(:,2))

falkner_skan function:

falkner_skan 函数:

function y_out = falkner_skan(x,y_in)

global beta

y_out(1,1) = y_in(2);
y_out(2,1) = y_in(3);
y_out(3,1) = -y_in(1)*y_in(3) - beta*(1-y_in(2)^2);

end

Thisand thisand thisthread does not seem to give me any guidance.

这个这个这个线程似乎没有给我任何指导。

采纳答案by Mattias Farnemyhr

It seems as though y_inis not a list but a float value. The error rises because you're trying to get an item with obj[x]of an object which doesn't support it.

似乎y_in不是列表而是浮点值。错误上升是因为您试图获取obj[x]不支持它的对象的项目。

Looking at the documentation for odeintit says that the input function should take two arguments, the first being your data object and the second should be a float. Your implementation of f_funcis therefore wrong.

查看 odeint文档,它说输入函数应该有两个参数,第一个是你的数据对象,第二个应该是一个浮点数。f_func因此,您的实现是错误的。

回答by Stav Bodik

NumPy has float 64 object which has item() function, np.float64(10.5).item()

NumPy 有 float 64 对象,它有 item() 函数,np.float64(10.5).item()

回答by Marjan Radfar

I had the same issue. According to documentation for odeint, in f_func(eta,y_in), change the order of eta and y_in, i.e. write it as f_func(y_in, eta) or set the argument tfirstto be True.

我遇到过同样的问题。根据odeint 的文档,在 f_func(eta,y_in) 中,更改 eta 和 y_in 的顺序,即将其写为 f_func(y_in, eta) 或将参数tfirst设置为True