AttributeError:'numpy.int32'对象没有属性'append'

Say*_*jee 5 python arrays numpy matrix scipy

首先让我展示一下我想做什么.
我有一个矩阵,

x = [1, 2, 1, 2, 3, 3, 2, 3, 1, 2]
Run Code Online (Sandbox Code Playgroud)

我想做的就是选择数组中重复数字的位置并将其打印在矩阵x_new中,其中:

x_new[0]= [0,2,8] (for similar position of repeated 1's in x)  
x_new[1]=[1,3,6,9](for similar position of repeated 2's in x)  
x_new[2]=[4,5,7] (for similar position of repeated 3's in x)
Run Code Online (Sandbox Code Playgroud)

到目前为止,我所做的是:

a=[]      
x=m[:,3]  #x=np.array([1, 2, 1, 2, 3, 3, 2, 3, 1, 2])     
ss=set([i for i in x if sum([1 for a in x if a == i]) > 1])     
lenss=len(ss)      
for ln in range(lenss):    
    for k in range(10):      
        if(x[k]== list(ss)[ln]):    
            print k     
        a.append(ln)    
    print 'next'    
Run Code Online (Sandbox Code Playgroud)

但是在a.append线上它显示:

'numpy.int32'对象没有属性'append'

谁能告诉我如何克服这个错误?谢谢

Ana*_*mar 5

Python 2.x中,您在list comprehension中使用的变量会泄漏到周围的命名空间中,因此a您在列表推导中使用的变量 -

ss=set([i for i in x if sum([1 for a in x if a == i]) > 1])  
Run Code Online (Sandbox Code Playgroud)

a您定义为列表的变量更改为元素x.

这方面的例子 -

>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> s = [i for i in range(5)]
>>> i
4
Run Code Online (Sandbox Code Playgroud)

您应该在列表comprehensin中使用不同的名称,如果您为变量使用更有意义的名称,这将有所帮助,这将降低遇到此类问题的风险.

这个问题不应该出现在Python 3.x中,就像在Python 3.x中一样,list comphrehension有自己的命名空间.