繁体   English   中英

Python列表删除多个项目

[英]Python List remove multiple 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]

雷姆(2,L)

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

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

while a in li == True:其实,这个检查一直以来返回False 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的情况。 我把那些练习留给你。

尝试将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

假设你要删除的所有实例aL ,你也可以只使用一个简单的列表理解:

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]

对于列表理解来说,这将是更好的工作。 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]

这可能不是您想要的行为。

只需跟踪索引号并使用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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM