删除Python列表中的元素

时间:2015-08-06 15:31:20

标签: python list

我的代码:

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

从我能读到的这段代码中,它应该只打印print ipList元素0和2,为什么我在第6行得到ValueError: list.remove(x): x not in list

1 个答案:

答案 0 :(得分: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

在找不到ip的匹配后,您仍然可能会搜索20次以上ip的其他匹配,即使您已将其删除,所以如果您再次获得匹配我会再次尝试删除它。

你可以在你的循环中使用any,任何人都会以与上述休息时间相同的方式找到匹配的短路:

for ip in reversed(ipList):
     if any(item in ip for item in blackList):
         ipList.remove(ip)

可以简单地成为:

ipList[:] = [ip for ip in ipList if not any(item in ip for item in blackList)]