简体   繁体   English

从列表中删除字符串

[英]Remove String From List

I have a list of strings containing IP addresses and DNS names with which I would like to remove the values beginning with "10." 我有一个包含IP地址和DNS名称的字符串列表,我希望删除以“10”开头的值。 only. 只要。 The sample data is as follows: 样本数据如下:

['www.example.com','1.2.3.4','4.3.2.1','example.net','10.1.1.10','10.1.1.11',...]

I thought this would be simple and started with the following: 我认为这很简单,并从以下开始:

for v in address:   
    test = re.match('(^\d+\.)',v)
    if test:
        if test.group(1) == '10.':
            address.remove(v)

The "10." “10” addresses were not removed although I didn't receive any errors (and did some t-shooting with "print address.remove(v)" which resulted in "None" for each "10." address. Leads me to believe the regex is wrong but it seems to work other than in this capacity. 虽然我没有收到任何错误,但是没有删除地址(并且使用“print address.remove(v)”进行了一些拍摄,导致每个“10.”地址都为“无”。让我相信正则表达式是错了但似乎除了这个能力之外还有效。

So I poked around with re.purge() - this didn't help either but don't think it's a factor in my problem. 所以我用re.purge()戳了一下 - 这也没有帮助,但不认为这是我问题的一个因素。 I also tried using del address[...] to no avail. 我也尝试使用del地址[...]无济于事。

Where have I gone wrong? 我哪里出错了?

Thanks very much for your attention. 非常感谢您的关注。

简单的方法是使用列表推导:

filtered = [ v for v in address if not v.startswith('10.') ]

One way is to create a new list using a list comprehension and str.startswith() : 一种方法是使用列表 str.startswith()str.startswith()创建一个新list

>>> [a for a in address if not a.startswith('10.')]
['www.example.com', '1.2.3.4', '4.3.2.1', 'example.net', '...']

This avoids using regular expressions and removing items during iteration , but does create a copy. 这避免了在迭代期间使用正则表达式和删除项目 ,但确实创建了副本。

What you've done wrong here is iterating over a list while you're changing the list. 你在这里做错了的是在你改变列表时迭代列表。 That means the iteration gets confused. 这意味着迭代会变得混乱。

See Removing Item From List - during iteration - what's wrong with this idiom? 请参阅从列表中删除项目 - 在迭代期间 - 这个成语有什么问题? for some suggestions on how to do this correctly. 有关如何正确执行此操作的一些建议。

If would probably make sense to test first that there is really an IP address in question. 如果首先测试确实存在有问题的IP地址可能是有意义的。

Otherwise 10.some-cdn.some-mighty-corp.com will be filtered out. 否则10.some-cdn.some-mighty-corp.com将被过滤掉。

Related post 相关文章

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

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