跳到主要内容

列表与元组

列表(list)和元组(tuple)都是有序序列。运维中最常见的是列表:存 IP 清单、待巡检主机、命令返回的多行结果。元组适合不可变的固定组合,如 (host, port)


列表基础

# 待 SSH 连接的主机列表
hosts = ["web-01", "web-02", "web-03", "db-01"]

print(len(hosts)) # 4
print(hosts[0]) # web-01(索引从 0 开始)
print(hosts[-1]) # db-01(最后一个)

# 追加与扩展
hosts.append("cache-01")
hosts.extend(["lb-01", "lb-02"])

切片批量取子集:

# 前两台 web
web_nodes = hosts[:2]
# 跳过第一台
rest = hosts[1:]
print(web_nodes, rest)

遍历与枚举

hosts = ["10.0.0.1", "10.0.0.2", "10.0.0.3"]

# 简单遍历
for ip in hosts:
print(f"检查 {ip} ...")

# 需要序号时用 enumerate(从 1 开始更符合运维习惯)
for idx, ip in enumerate(hosts, start=1):
print(f"[{idx}/{len(hosts)}] 巡检 {ip}")

列表推导式

用一行生成新列表,适合过滤与映射:

ports = [80, 443, 8080, 8443, 22]

# 只保留 Web 相关端口
web_ports = [p for p in ports if p in (80, 443, 8080, 8443)]

# 生成 "host:port" 字符串
endpoints = [f"192.168.1.10:{p}" for p in web_ports]
print(endpoints)
# ['192.168.1.10:80', '192.168.1.10:443', ...]

排序与去重

# 按磁盘使用率降序(模拟巡检结果)
disk_usage = [("web-01", 45), ("web-02", 92), ("db-01", 78)]

sorted_usage = sorted(disk_usage, key=lambda x: x[1], reverse=True)
for host, pct in sorted_usage:
flag = "⚠️" if pct > 85 else "OK"
print(f"{host}: {pct}% {flag}")

# 去重 IP(保持顺序需用 dict,集合会打乱顺序)
raw_ips = ["10.0.0.1", "10.0.0.2", "10.0.0.1"]
unique_ips = list(dict.fromkeys(raw_ips))
print(unique_ips) # ['10.0.0.1', '10.0.0.2']

元组:不可变记录

# 单条连接信息,不希望被意外修改
conn = ("10.0.0.5", 22, "deploy")
host, port, user = conn # 解包

# 元组作 dict 的 key(列表不行)
service_map = {
("nginx", 80): "running",
("nginx", 443): "running",
("redis", 6379): "stopped",
}

for (name, port), status in service_map.items():
print(f"{name}:{port} -> {status}")

函数返回多个值时,实际返回的是元组:

def check_port(host: str, port: int) -> tuple[bool, str]:
# 模拟检查结果
ok = port in (80, 443)
return ok, "open" if ok else "closed"

success, detail = check_port("web-01", 8080)
print(success, detail)

实战:批量生成 inventory 行

groups = {
"web": ["10.0.1.10", "10.0.1.11"],
"db": ["10.0.2.20"],
}

lines = []
for group, ips in groups.items():
for ip in ips:
lines.append(f"{ip} ansible_host={ip} group={group}")

print("\n".join(lines))

小结

类型可变典型用途
listIP 列表、日志行、巡检结果
tuple固定字段组合、函数多返回值

下一章学习 字典与集合,管理主机资产与配置映射。