以数字范围而不是单位开头

Startswith with a range of number instead an unit

ip = a list of ips
ipf = list(filter(lambda x: x if not x.startswith(str(range(257,311))) else None, ip))

有没有可能做这样的事情?我测试了它,但它不起作用。 我想从 "ip" 列表中删除所有以 256.257.258.ecc... 到 310.

开头的 ip

不,str.startswith() 不采用范围。

您必须解析出第一部分并将其作为整数进行测试;列表理解也更容易完成过滤:

[ip for ip in ip_addresses if 257 <= int(ip.partition('.')[0]) <= 310]

另一种方法是使用 ipaddress library;它会拒绝任何带有 ipaddress.AddressValueError 异常的无效地址,并且由于以任何超过 255 开头的地址都是无效的,您可以轻松地选择它来过滤掉您的无效地址:

import ipaddress

def valid_ip(ip):
    try:
        ipaddress.IPv4Address(ip)
    except ipaddress.AddressValueError:
        return False
    else:
        return True

[ip for ip in ip_addresses if valid_ip(ip)]