Python AttributeError 列表对象没有属性添加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40567103/
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
AttributeError list object has no attribute add
提问by Abbas Zahid
Python is new for me and I am doing some machine learning code using python. My scenario is that I am reading data from my sql and trying to give a shape to this data so i can use it for MLP training.
Python 对我来说是新的,我正在使用 Python 做一些机器学习代码。我的场景是我正在从我的 sql 中读取数据并尝试为这些数据提供一个形状,以便我可以将它用于 MLP 训练。
My code is below:
我的代码如下:
connection = mysql.connector.connect(host='localhost', port=3306, user='root', passwd='mysql', db='medicalgame')
cur = connection.cursor()
query = ""
cur.execute(query)
# X_train will be a list of list and later we'll convert it to a numpy ndarray
X_train = []
for row in cur:
X_train.add(row)
connection.close()
X_train should be ready
X_train = np.asarray(X_train)
print 'The shape of X_train is', X_train.shape
During debug the query result i got is like this: (6, 1, 1, 1, 2, u'F', 1, 0, 0, 19) Can anyone help me how can, I fix the error and give shape to my X_train, so that MLP accept it as an input ?
在调试期间,我得到的查询结果是这样的: (6, 1, 1, 1, 2, u'F', 1, 0, 0, 19) 任何人都可以帮助我怎么做,我修复错误并赋予形状我的 X_train,以便 MLP 接受它作为输入?
回答by Jean-Fran?ois Fabre
the message is clear. list
has no method add
because it is ordered(it has a dunder __add__
method but that's for addition between lists). You can insert
but you want to append
. So the correct way is:
信息很明确。list
没有方法,add
因为它是有序的(它有一个 dunder__add__
方法,但这是在列表之间添加的)。你可以,insert
但你想append
。所以正确的做法是:
X_train = []
for row in cur:
X_train.append(row)
BUT the preferred way converting to a list directly (iterating on cur
elements to create your list in a simple and performant way):
但是直接转换为列表的首选方式(迭代cur
元素以简单且高效的方式创建列表):
X_train = list(cur)
BUT you cannot do that since your list contains bogus data. Fortunately, you can filter them out in a nested list comprehension like this:
但是您不能这样做,因为您的列表包含虚假数据。幸运的是,您可以像这样在嵌套列表理解中过滤掉它们:
X_train = [[x for x in r if type(x)==int] for r in cur]
this builds your list of lists but filters out non-integer values and feeding it to numpy.asarray
yields (with your sample data):
这会构建您的列表列表,但会过滤掉非整数值并将其提供给numpy.asarray
产量(使用您的示例数据):
[[ 6 1 1 1 2 1 0 0 19]
[ 6 1 1 1 2 1 0 0 14]]