JavaEar 专注于收集分享传播有价值的技术资料

AttributeError: 'numpy.int32' object has no attribute 'append'

First let me show what i want to do.
I have a matrix,

x = [1, 2, 1, 2, 3, 3, 2, 3, 1, 2]

All i want do is to select position of repeated numbers in the array and print it in a matrix x_new where :

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)

Until now what i have done is :

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])     
for ln in range(lenss):    
    for k in range(10):      
        if(x[k]== list(ss)[ln]):    
            print k     
    print 'next'    

But at the a.append line it's showing:

'numpy.int32' object has no attribute 'append'

Can anyone please tell me how to overcome this error? Thanks


  1. In Python 2.x , the variables you use inside list comprehension leak into the surrounding namespace, so the a variable you use in the list comprehension -

    ss=set([i for i in x if sum([1 for a in x if a == i]) > 1])  

    Changes the a variable you defined as list to elements of x.

    Example for this -

    >>> 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

    You should use different name inside the list comprehensin , and it would help if you use more meaningful names for your variables, that would reduce the risk of running into such issues.

    This issue should not occur in Python 3.x , as in Python 3.x , list comphrehension has a namespace of its own.

  2. 参考答案2
  3. this is numpy solution to your problem

    x = np.array(x)
    unique = np.unique(x)
    [np.where(x == unique_num) for unique_num in unique]
  4. 参考答案3
  5. You reassign your variable a: In the first line a=[], but you use again a in ss generator:

    ss=set([i for i in x if sum([1 for a in x if a == i]) > 1])

    Simple example:

    >>> [x for x in range(10)]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> x