简体   繁体   中英

Python ValueError: list.remove(x): x not in list

def switch(g, p,n):
final = []
for i in range(len(p)):
    d = list(range(n))
    d.remove(g[i])
    d.remove(p[i])

    final.append(d)

return final

switch([2, 3, 0], [[1, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 5, 6, 7, 8,
9],[1, 2, 4, 5, 6, 7, 8, 9]],11)

But when I run this code I get the following error:

ValueError                                Traceback (most recent call last) <ipython-input-151-72e1cc5c9abf> in <module>()
     10     return final
     11 
---> 12 switch([2, 3, 0], [[1, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 5, 6, 7, 8, 9],[1, 2, 4, 5, 6, 7, 8, 9]],11)



<ipython-input-151-72e1cc5c9abf> in switch(g, p, n)
      4         d = list(range(n))
      5         d.remove(g[i])
----> 6         d.remove(p[i])
      7 
      8         final.append(d)

ValueError: list.remove(x): x not in list

What am I doing wrong here? I just want the numbers of g and p removed from the list and that I get the number that is left as output.

Looks like you are trying to remove an array from a list

In [259]: alist = [np.arange(3), np.ones(3,int),np.array([4,3,2])]
In [260]: alist
Out[260]: [array([0, 1, 2]), array([1, 1, 1]), array([4, 3, 2])]
In [261]: alist.remove(alist[1])
....
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The problem is that equality tests on arrays returns a boolean array

In [262]: alist[1]==alist[0]
Out[262]: array([False,  True, False])
In [263]: alist[1]==alist[1]
Out[263]: array([ True,  True,  True])

But the list remove requires a simple True or False, not an ambiguous array.

That kind of remove works with a list of lists or list of tuples

In [264]: alist = [[0,1,2],[1,1,1],[4,3,2]]
In [265]: alist.remove(alist[1])
In [266]: alist
Out[266]: [[0, 1, 2], [4, 3, 2]]

Do you really need a list of arrays?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM