首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Python 生成連續 IP 地址列表:從 10.10.10.1 到 10.10.10.10 的實現

     編輯:程式設計疑難解答

需求

將 IP 范圍 10.10.10.1-10.10.10.10 轉為列表,供 for 循環遍歷使用。

實現代碼

ips = []
for i in range(1, 11):  # Python 3 使用 range,Python 2 用 xrange
    ips.append("10.10.10.%d" % i)
print(ips)
# 輸出: ['10.10.10.1', '10.10.10.2', ..., '10.10.10.10']

進階:通用函數

def ip_range(start_ip, end_ip):
    """生成 IP 范圍列表,假設前三段相同,僅最后一段變化"""
    prefix = '.'.join(start_ip.split('.')[:3])
    start = int(start_ip.split('.')[-1])
    end = int(end_ip.split('.')[-1])
    return [f"{prefix}.{i}" for i in range(start, end + 1)]

# 使用示例
print(ip_range("10.10.10.1", "10.10.10.10"))

注意

  • Python 2 使用 xrange 節省內存,Python 3 range 已是惰性序列。
  • 若需支持完整 IP 範圍(跨段),建議使用 ipaddress 標準庫(Python 3.3+)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved