在python中从列表中删除特定的相似元素

2024-04-29 18:42:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的清单

list1=['abc','oops','#exclude=10','exclude=java* kln*','smith','johns']

我正试图用下面的代码删除包含单词“exclude”的元素。你知道吗

x=0  

for i in list1:

    if 'exclude' in i:
        list1.pop(x)
    x+=1 

print list1

当我运行程序时,它正在删除第一个exclude,而不是第二个。请让我知道如何删除所有exclude,我犯了什么错误?你知道吗


Tags: 代码in元素forifjava单词exclude
3条回答

你经历这种行为的原因是你在迭代它的时候正在变异。当你弹出#exclude=10list1x == 2弹出元素后

     list1 == ['abc','oops','exclude=java* kln*','smith','johns']

现在x增加到3,但是在弹出之后list1[3]==smith,而您希望它是exclude=java* kln*,就像您的原始版本list1。你知道吗

这里有一个简单的解决方案:

import re
list1=['abc','oops','#exclude=10','exclude=java* kln*','smith','johns']
regex = re.compile('.*exclude.*')
okay_items = [x for x in list1 if not regex.match(x)]
print(okay_items)

在您的解决方案中,您使用了pop()并根据documentation

list.pop([i]):

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.

因为当删除第一个元素列表时,它是元素,这就是为什么会发生这种情况。你知道吗

你可以试试这是:-

list1=['abc','oops','#exclude=10','exclude=java* kln*','smith','johns']
new_ls = [list1.index(x) for x in list1 if 'exclude' in x]
for i in reversed(new_ls):
    list1.pop(i)
print(list1)

相关问题 更多 >