简体   繁体   English

Python ValueError:list.remove(x):x不在列表中

[英]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. 我只想从列表中删除g和p的数字,然后得到剩下的数字作为输出。

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. 但是列表remove需要一个简单的True或False,而不是一个不明确的数组。

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? 您是否真的需要一个数组列表?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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