删除所有具有特定值的实例

时间:2019-09-28 05:50:44

标签: python python-3.x list list-comprehension

我正在尝试从列表中删除特定值的所有实例,然后将其余列表项下移。该代码在某些情况下有效,但在其他情况下则无效。例如:

print(myremove([7, 'B', 1, 8, 3, 'B'], 6, 'B')) # Gets what I want 
print(myremove(['C', 'C', 7, 'C', 4, 'C'], 6, 'C')) # Does not

我要做的一件事是删除该项目的所有实例,然后将所有剩余的元素向下移动。

   def myremove(mylist, elements, item):
        for i in range(elements):
            if mylist[i] == item:
                 mylist[i] = None
                 elements-= 1

        for i in range(elements):
            if mylist[i] is None:
                for j in range(i, elements):
                    mylist[j] = mylist[j + 1]
                    mylist[elements] = None

        return mylist

1 个答案:

答案 0 :(得分:0)

解决方案

您可以使用简单的pythonic列表理解:

vals = ['C', 'C', 7, 'C', 4, 'C']
droplist = [6, 'C']
[x for x in vals if (x not in droplist)]

修改后的myremove()功能

def myremove(vals, droplist = None):
    if droplist is None:
        droplist = [None, ]
    return [x for x in vals if (x not in droplist)]

print(myremove([7, 'B', 1, 8, 3, 'B'], droplist=[8, 'B']))
print(myremove(['C', 'C', 7, 'C', 4, 'C'], droplist=[6, 'C']))

输出

[7, 1, 3]
[7, 4]