我的代码:
ipList = ["192.168.0.1", "sg1234asd", "1.1.1.1", "test.test.test.test"]
blackList = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_", ","]
for ip in ipList:
for item in blackList:
if (item in ip) == True:
ipList.remove(ip)
else:
pass
print ipList
Run Code Online (Sandbox Code Playgroud)
从我能读到的这段代码来看,它应该只打印print ipList元素0和2,为什么我会ValueError: list.remove(x): x not in list在第6行给出?
你有两个问题,你不应该迭代并从列表中删除元素,break当你找到匹配时你也应该是内循环,你不能删除相同的元素28次,除非你重复28次:
ipList = ["192.168.0.1", "sg1234asd", "1.1.1.1", "test.test.test.test"]
blackList = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_", ","]
for ip in reversed(ipList):
for item in blackList:
if item in ip:
ipList.remove(ip)
break
print ipList
Run Code Online (Sandbox Code Playgroud)
在没有破坏的情况下,在找到匹配后ip,ip即使你已经删除它,你仍然可能会搜索20次以上的其他匹配,所以如果你得到另一个匹配,你将尝试再次删除它.
你可以使用any你的循环,任何会发现匹配的短路,就像上面的休息一样:
for ip in reversed(ipList):
if any(item in ip for item in blackList):
ipList.remove(ip)
Run Code Online (Sandbox Code Playgroud)
这可以简单地成为:
ipList[:] = [ip for ip in ipList if not any(item in ip for item in blackList)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |