用于删除列表的Python代码不起作用

问题描述 投票:0回答:1

以下函数应删除列表中的元素,如果该元素与第一个列表重叠。但是,它仅适用于第一个示例(a和b1)。与其他人甚至不发送错误消息,我也不知道问题出在哪里。有人可以指出我正确的方向吗?

           def funct(firstone, secondone ):
              counter = 0
              while secondone != [] and counter < len(firstone):
                 if firstone [counter] in secondone :
                    del(secondone[ secondone .index(firstone[counter ])])
                     counter += 1
                 return secondone
a = [0, 1, 2]
b1 = [1, 2, 0]
b2 = [-1, 1, 1]
b3 = [0,0,2]
print(funct(a, b1)) 
print(funct(a, b2)) 
print(funct(b3, a))
python list
1个回答
0
投票

当条件为False时,您需要继续for循环,否则您将始终在第一次迭代时返回

          while secondone != [] and counter < len(firstone):
              if firstone[counter] in secondone :
                  del(secondone[secondone.index(firstone[counter])])
                  counter += 1
              else:
                  continue
          return secondone
© www.soinside.com 2019 - 2024. All rights reserved.