'list' object has no attribute 'shape'

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

how to create an array to numpy array?

def test(X, N):     [n,T] = X.shape     print "n : ", n     print "T : ", T    if __name__=="__main__":      X = [[[-9.035250067710876], [7.453250169754028], [33.34074878692627]], [[-6.63700008392334], [5.132999956607819], [31.66075038909912]], [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]]]     N = 200     test(X, N) 

I am getting error as

AttributeError: 'list' object has no attribute 'shape' 

So, I think I need to convert my X to numpy array?

回答1:

Use numpy.array to use shape attribute.

>>> import numpy as np >>> X = np.array([ ...     [[-9.035250067710876], [7.453250169754028], [33.34074878692627]], ...     [[-6.63700008392334], [5.132999956607819], [31.66075038909912]], ...     [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]] ... ]) >>> X.shape (3L, 3L, 1L) 

NOTE X.shape returns 3-items tuple for the given array; [n, T] = X.shape raises ValueError.



回答2:

import numpy X = numpy.array(the_big_nested_list_you_had) 

It's still not going to do what you want; you have more bugs, like trying to unpack a 3-dimensional shape into two target variables in test.



回答3:

list object in python does not have 'shape' attribute because 'shape' implies that all the columns (or rows) have equal length along certain dimension.

Let's say list variable a has following properties: a = [[2, 3, 4] [0, 1] [87, 8, 1]]

it is impossible to define 'shape' for variable 'a'. That is why 'shape' might be determined only with 'arrays' e.g.

b = numpy.array([[2, 3, 4]                 [0, 1, 22]                 [87, 8, 1]]) 

I hope this explanation clarifies well this question.



回答4:

Alternatively, you can use np.shape(...)

For instance:

import numpy as np

a=[1,2,3]

and np.shape(a) will give an output of (3,)



回答5:

if the type is list, use len(list) and len(list[0]) to get the row and column.

l = [[1,2,3,4], [0,1,3,4]] 

len(l) will be 2 len(l[0]) will be 4



回答6:

firstly u have to import numpy library (refer code for making a numpy array) shape only gives the output only if the variable is attribute of numpy library .in other words it must be a np.array or any other data structure of numpy. Eg.

`>>> import numpy >>> a=numpy.array([[1,1],[1,1]]) >>> a.shape (2, 2)` 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!