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

时间:2018-02-23 06:39:00

标签: 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。请告诉我如何删除所有public class MoneyClass { [Column("Money")] public decimal MyDbValue { get; set; } // You existing db-property [NotMapped] public decimal MyCodeValue // some property to access within you code { get { return this.MyDbValue; } set { decimal newDbValue = decimal.Round(value, 2); if (this.MyDbValue != newDbValue) { Console.WriteLine("Change! Old: {0}, New: {1}, Input: {2}", this.MyDbValue, newDbValue, value); this.MyDbValue = newDbValue; } } } } static void Main(params string[] args) { MoneyClass dbObj = new MoneyClass() { MyCodeValue = 123.456M }; Console.WriteLine(dbObj.MyDbValue); dbObj.MyCodeValue = 123.457M; // won't change anything Console.WriteLine(dbObj.MyDbValue); dbObj.MyCodeValue = 123.454M; // will change because of 3rd decimal value 4 Console.WriteLine(dbObj.MyDbValue); dbObj.MyCodeValue = 123.46M; // will change Console.WriteLine(dbObj.MyDbValue); } 以及我正在做的错误是什么?

5 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案:

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]):

     

删除列表中给定位置的项目,然后将其返回。如果   没有指定索引,a.pop()删除并返回最后一项   清单。

答案 1 :(得分:1)

您遇到此类行为的原因是您在迭代它时正在改变list1。弹出#exclude=10时 来自list1x == 2,一旦元素被弹出

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

现在x增加到3,但弹出后增加list1[3]==smith,而您原来的版本exclude=java* kln*中的增量为list1

答案 2 :(得分:0)

试试这个,

>>> list1=['abc','oops','#exclude=10','exclude=java* kln*','smith','johns']
>>> [i for i in list1 if 'exclude' not in  i]
['abc', 'oops', 'smith', 'johns']
>>> 

原始列表中没有列表理解和效果的简单方法,

>>> list1=['abc','oops','#exclude=10','exclude=java* kln*','smith','johns']
>>> for i in filter(lambda x: 'exclude' in x, list1):
...   list1.remove(i)
... 
>>> list1
['abc', 'oops', 'smith', 'johns']
>>> 

答案 3 :(得分:0)

方法pop()从列表中删除并返回最后一个对象或obj。

相反,您可以创建一个新列表,其中不包含"exclude"这样的字符串。

list1=['abc','oops','#exclude=10','exclude=java* kln*','smith','johns']
listWithoutExclude = []
for each in list1:
    if "exclude" not in each:
        listWithoutExclude.append(each)
print listWithoutExclude

答案 4 :(得分:0)

因为在删除第一个元素列表时会移动它的元素,这就是发生这种情况的原因。

您可以尝试:

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)
相关问题