我认为poke的答案很棒。但是,如果您要在循环中生成和使用它们,我只需创建一个无限迭代器并对其进行过滤:
# Same as your function, but without the bugs
def gen_ip():
return '.'.join(str(random.randrange(256)) for _ in range(4))
# Obviously not the real logic; that's left as an exercise to the reader of
# https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
def is_private_ip(ip):
return not ip.startswith('2')
# Now this is an infinite iterator of non-private IP addresses.
ips = ifilterfalse(repeatfunc(gen_ip), is_private_ip)
现在你可以获得 10 个这样的 IP:
>>> take(10, ips)
['205.150.11.90',
'203.233.175.192',
'211.241.64.223',
'250.224.20.172',
'203.26.103.176',
'20.107.5.214',
'204.181.205.180',
'234.24.178.180',
'22.225.212.59',
'237.122.140.163']
我已经使用take
and repeatfunc
from the recipes in the itertools
docs和ifilterfalse
fromitertools
本身。