# 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,如下所示:
我使用了来自recipes in the ^{} docs 的
take
和repeatfunc
,以及来自itertools
本身的ifilterfalse
。你知道吗更有效的解决方案是创建一个所有可能地址(或地址的一部分)的列表,在这个数组中生成索引,并根据这个索引选择元素。像这样:
相关问题 更多 >
编程相关推荐