值错误:列表.删除(x) :x不在列表中,但我看不到fau

2024-03-28 14:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

但当我运行此代码时,会出现以下错误:

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

我做错什么了?我只想把g和p的数字从列表中删除,然后得到作为输出的数字。你知道吗


Tags: inforinputlenreturndefipythonrange
1条回答
网友
1楼 · 发布于 2024-03-28 14:26:35
def switch(g, p, n):
    out = []
    for exclude, exclude_list in zip(g, p):
        out.append([x for x in range(n) if x != exclude and x not in exclude_list])
    return out

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

我们不是从列表中删除项,而是只使用未排除的项创建子列表。你知道吗

相关问题 更多 >