我正在尝试从列表中删除多次出现的值。输出不会删除任何所需的项目。
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]
答案 0 :(得分:5)
您的代码中有2个错误。第一个是
while a in li == True:
实际上,此检查始终返回错误,因为li == True
错误。
实际应该是while (a in li) == True:
或while a in li:
此外,如果您尝试仅删除a
的重复次出现(即首次出现a
),则列表理解不适合您的需求。您必须在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
上面的代码段未涵盖列表为空的边缘情况,或者案例a
不在列表中。我会把这些练习留给你。
答案 1 :(得分:2)
尝试将while条件更改为while a in li
def rem(a,li):
try:
while a in li:
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)
通常,如果要从列表中删除重复项,则可以使用内置的set
。
答案 2 :(得分:2)
假设您要从a
中删除L
的所有实例,您还可以使用简单的列表理解:
def rem(a,li):
return [x for x in li if x != a]
L = [1,2,3,45,3,2,3,3,4,5]
print(rem(2,L))
哪个输出:
[1, 3, 45, 3, 3, 3, 4, 5]
答案 3 :(得分:2)
这对于列表理解来说会更好。
L[:] = [a for a in L if a not in (2,)]
分配给切片会使列表发生变异。
我正在更新我的答案,以解释您的问题允许的各种解释 并且通过接受同时使用字符串和多个值来使其更加通用。
def removed(items, original_list, only_duplicates=False, inplace=False):
"""By default removes given items from original_list and returns
a new list. Optionally only removes duplicates of `items` or modifies
given list in place.
"""
if not hasattr(items, '__iter__') or isinstance(items, str):
items = [items]
if only_duplicates:
result = []
for item in original_list:
if item not in items or item not in result:
result.append(item)
else:
result = [item for item in original_list if item not in items]
if inplace:
original_list[:] = result
else:
return result
Docstring扩展名:
"""
Examples:
---------
>>>li1 = [1, 2, 3, 4, 4, 5, 5]
>>>removed(4, li1)
[1, 2, 3, 5, 5]
>>>removed((4,5), li1)
[1, 2, 3]
>>>removed((4,5), li1, only_duplicates=True)
[1, 2, 3, 4, 5]
# remove all duplicates by passing original_list also to `items`.:
>>>removed(li1, li1, only_duplicates=True)
[1, 2, 3, 4, 5]
# inplace:
>>>removed((4,5), li1, only_duplicates=True, inplace=True)
>>>li1
[1, 2, 3, 4, 5]
>>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
>>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
>>>li2
['abc', 'def', 'ghi']
"""
您应该清楚自己真正想做什么,修改现有列表或制作新列表 缺少的具体项目。如果您有第二个引用指向,那么区分它是很重要的 到现有的清单。如果你有,例如......
li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
# then rebind li1 to the new list without the value 4
li1 = removed(4, li1)
# you end up with two separate lists where li2 is still pointing to the
# original
li2
# [1, 2, 3, 4, 4, 5, 5]
li1
# [1, 2, 3, 5, 5]
这可能是您想要的行为,也可能不是。
答案 4 :(得分:1)
只需跟踪索引编号并使用del
简单方法:
L = [1,2,3,45,3,2,3,3,4,5]
def rem(a,li):
for j,i in enumerate(li):
if a==i:
del li[j]
return li
print(rem(2,L))
输出:
[1, 3, 45, 3, 3, 3, 4, 5]