Python列表删除多个项目 [英] Python List remove multiple items
问题描述
我正在尝试从列表中删除多次出现的值.输出不会删除任何所需的项.
I am trying to remove multiple occurrences of a value from a list.The output does not remove any of the desired items.
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)
试用功能示例:
L = [1,2,3,45,3,2,3,3,4,5]
rem(2,L)
输出:更新后的列表:[1、2、3、45、3、2、3、3、4、5]
Output: Updated list: [1, 2, 3, 45, 3, 2, 3, 3, 4, 5]
推荐答案
您的代码中有2个错误.第一个是
There are 2 mistakes in your code. The first one is
while a in li == True:
实际上,由于li == True
为 False ,因此此检查始终返回 False .
while a in li == True:
In fact, this check always returns False since li == True
is False.
它实际上应该是while (a in li) == True:
或while a in li:
此外,如果您尝试仅删除重复个出现的a
(即,将第一个出现的a
留在其中),则列表理解将不符合您的需求.您必须在rem()
函数内添加一个附加检查,以捕获第一次出现的a
,然后然后执行循环:
Also, if you are trying to delete only repeated occurrences of a
(i.e. leave the first occurrence of a
in) then list comprehension won't suit your needs. You will have to add an additional check inside your rem()
function that catches the first occurrence of a
and then executes your loop:
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
上面的代码段不涉及列表为空或列表中没有cc的情况.我把那些练习留给你.
The code snippet above does not cover the edge cases where the list is empty, or the case a
is not in the list. I'll leave those exercises to you.
这篇关于Python列表删除多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!