Python列表删除多个项目

0 python list python-3.x

我试图从列表中删除多次出现的值。输出不会删除任何所需的项。

def rem(a,li):
try:
    while a in li == True:
        li.remove(a)
    print('Updated list: ',li)
except ValueError:
    print(a,' is not located in the list ',li)
Run Code Online (Sandbox Code Playgroud)

尝试功能的示例:

L = [1,2,3,45,3,2,3,3,4,5]
Run Code Online (Sandbox Code Playgroud)

雷姆(2,L)

输出:更新列表:[1、2、3、45、3、2、3、3、4、5]

Bar*_*tal 5

您的代码中有2个错误。第一个是

while a in li == True:实际上,此检查始终返回False,因为它li == TrueFalse

它实际上应该是while (a in li) == True:,或while a in li:

同样,如果您仅尝试删除重复出现的a(即保留ain 的第一个出现),则列表理解将不符合您的需求。您必须在rem()函数内添加一个附加检查,以捕获第一次出现的a然后执行循环:

def rem(a, li):
  list_length = len(li)
  i = 0
  while (li[i] != a) and (i < list_length):
    i += 1              # skip to the first occurrence of a in li
  i += 1                # increment i 
  while i < list_length:
    if li[i] == a:
      del li[i]
      print('Updated list: ', li)
      list_length -= 1          # decrement list length after removing occurrence of a
    else:
      i += 1
Run Code Online (Sandbox Code Playgroud)

上面的代码段未涵盖列表为空或列表中未包含案例的极端情况a。我把那些练习留给你。