简体   繁体   English

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

[英]Remove elements from list based on specific content

I have the following 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'] ['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']

I need to remove all elements that contain '|locationInherited=true', so both '10.20.30.40|locationInherited=true' & '8.8.8.8|locationInherited=true' need to be removed so all that is left in the list is ['10.10.10.10', '20.20.20.20', '30.30.30.30', '40.40.40.40'] 我需要删除所有包含'| locationInherited = true'的元素,因此'10 .20.30.40 | locationInherited = true'和'8.8.8.8 | locationInherited = true'都需要删除,因此列表中剩下的全部是[ '10 .10.10.10','20.20.20.20','30.30.30.30','40.40.40.40']]

I have tried 我努力了

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

And

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

Neither produce an error but neither remove all the necessary elements. 既不会产生错误,也不会删除所有必要的元素。

Try this: 尝试这个:

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

output: 输出:

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

Using module re , you can easily find a substring inside a string. 使用模块re ,您可以轻松地在字符串中找到子字符串。

See the docs 查看文件

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

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