我有以下代码,我想做的是创建一个小函数,以便当输入 IP 范围(其中包含:)时,所有范围都会附加到列表中。
collected_ips = []
while True:
query = input("IP:\t")
if not query:
break
elif len(query.split('.'))==4:
temp = query.split('.')
#result1 = all([i.isdigit() for i in t]) #must be True
if query.find(":")==-1:
try:
result2 = all([0<=int(i)<=255 for i in temp])
if result2:
collected_ips.append(query)
except ValueError:
print("Please Fix Input")
elif len(x.split(":"))==2:
#function here
#append to collected_ips
else:
print("Please Fix Input")
else:
print("Please Fix Input")
输入示例:
123.123.30.20:50
输出:
['123.123.30.20,'123.123.30.21'...'123.123.30.50']
输入示例:
123.123.20:50.30
输出:
['123.123.20.30','123.123.21.30',...'123.123.50.30']
最佳答案
这是一种使用范围
生成两个范围之间的数字的方法:
def spread_ip_range(ip):
splits = ip.split('.')
indx = next((i for i, x in enumerate(splits) if ':' in x), -1)
lst = []
if indx != -1:
_from, to = splits[indx].split(':')
ranges = range(max(0, int(_from)), min(255, int(to)) + 1))
for r in ranges:
s = '.'.join(splits[:indx]) + '.' + str(r)
if splits[indx+1:]:
s += '.' + '.'.join(splits[indx+1:])
lst.append(s)
return lst
用法:
>>> spread_ip_range('123.123.20:50.30')
['123.123.20.30', '123.123.21.30', '123.123.22.30', ......, '123.123.49.30', '123.123.50.30']
-
>>> spread_ip_range('123.123.30.20:50')
['123.123.30.20', '123.123.30.21', '123.123.30.22', ......, '123.123.30.49', '123.123.30.50']
关于python - 将 IP 范围扩展至列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56414979/