python - 将 IP 范围扩展至列表

标签 python list

我有以下代码,我想做的是创建一个小函数,以便当输入 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/

相关文章:

java - 开源 ETL 框架

python - 将相同的字符串附加到 Python 中的字符串列表

python - 使用变量进行切片时如何使用单冒号?

python - Plotly 图形组件无法接受视口(viewport)单位来设置文本注释字体大小

python - text.replace(punctuation ,'' ) 不会删除 list(punctuation) 中包含的所有标点符号?

python - 在条件列表理解中使用 or 语句来过滤数据框中的列

C++ 用 ostream 以外的东西重载运算符 <<

php - Php/HTML 中的无序列表

python - Pygame:如何在非矩形裁剪区域内绘制

python - ctypes vs _ctypes - 为什么后者存在?