You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python遍历列表检查主机名是否包含指定类型字符串?

遍历列表匹配主机名中的类型字符串

你可以直接遍历host_type列表,检查每个类型字符串是否存在于主机名中,这样后续新增主机类型只需要修改列表,不用调整条件判断代码,更简洁易维护。

如果想和原if-elif逻辑保持一致(只匹配第一个符合条件的类型),可以这样写:

from os import uname

host = uname()[1]
host_type = ["control", "consumer", "search", "hub"]

# 遍历列表,检查每个类型是否在主机名中
for ht in host_type:
    if ht in host:
        print(ht)
        break  # 找到第一个匹配项后停止遍历

如果你的主机名可能包含多个类型字符串,需要全部打印出来,去掉break即可:

from os import uname

host = uname()[1]
host_type = ["control", "consumer", "search", "hub"]

for ht in host_type:
    if ht in host:
        print(ht)

内容的提问来源于stack exchange,提问作者eekfonky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:07:25