根据特定内容从列表中删除元素

时间:2017-09-15 00:36:19

标签: python list

我有以下列表:

[' 10.10.10.10',' 20.20.20.20',' 30.30.30.30',' 10.20.30.40 | locationInherited = true',' 40.40.40.40',' 8.8.8.8 | locationInherited = true']

我需要删除包含' | locationInherited = true'的所有元素,以便' 10.20.30.40 | locationInherited = true' &安培; ' 8.8.8.8 | locationInherited =真'需要删除,所以列表中的所有内容都是[' 10.10.10.10',' 20.20.20.20',' 30.30.30.30', ' 40.40.40.40']

我试过了

for elem in list:
    if '|locationInherited=true' in elem:
        list.remove(elem)

while list.count('|locationInherited=true') > 0:
            list.remove('|locationInherited=true')

既不会产生错误,也不会删除所有必需的元素。

1 个答案:

答案 0 :(得分:1)

试试这个:

import re
ips = ['10.10.10.10', '20.20.20.20', '30.30.30.30',
       '10.20.30.40|locationInherited=true', '40.40.40.40', '8.8.8.8|locationInherited=true']

for i in ips:
    if re.search('.*\|locationInherited=true', i):
        ips.pop(ips.index(i))

输出:

['10.10.10.10', '20.20.20.20', '30.30.30.30', '40.40.40.40']

使用模块re,您可以轻松地在字符串中找到子字符串。

See the docs