使用for循环打印 - Python

2 投票
2 回答
1182 浏览
提问于 2025-04-16 08:40

我对Python或者任何编程语言都非常陌生。现在我在用for循环打印一些文本和列表中的值时遇到了困难。我想要的效果是,把列表中的第一个项目和“shutdown”这个文本一起打印出来,然后再用“no shutdown”重复一次。同时,我还希望能在这两次输出之间插入任何文本。请给我一些建议。以下是更多信息……

当前输出:这是我不想要的结果

interface Vlan100
 shut
 no shut
interface Vlan108
 shut
 no shut

期望的输出:

# 第一次打印:

********* THIS IS INTERFACE OUTPUT WITH "SHUTDOWN" **********
interface Vlan100
 shutdown
interface Vlan108
 shutdown

** 这是带有“NO SHUTDOWN”的接口输出 ***

*# Second time printing:*
interface Vlan100
 no shutdown
interface Vlan108
 no shutdown

代码摘录,简化以便于阅读。

for i in servicetypes:
<snip>
<snip>
elif "ipv4 address" in i or "ipv4 address 8" in i or " ipv4 address 213" in i:
    i = re.sub(r'encapsulation dot1Q \d+\n\s','',i)
    i = re.sub(r'TenGigE[0-9]/[0-9]/[0-9]/[0-9].','Vlan',i)
    internet = i.split("\n")
    print internet[1]
    print " shut"
    print " no shut"

2 个回答

1

现在你是这样做的:

print " shut"
print " no shut"

结果是:

shut
no shut

这很正常。如果你想在关闭时打印“shut”,而在不关闭时打印“no shut”,你需要进行一个测试:

if shutdown(interface):
    print "shut"
else:
    print "no shut"

或者类似的东西。


(编辑:好的,你已经回答了这个问题,你想要上面的内容,而不是下面的,所以忽略这一部分。

不过,如果你只是想打印

interface Vlan100
 shut
interface Vlan108
 shut
interface Vlan100
 no shut
interface Vlan108
 no shut

那么你需要两个独立的循环。

不过,你想要的内容或者你正在尝试做的事情并不是很清楚。)

好的,这里是如何得到那个输出的:

for what in (" shut", " no shut"):
    for iface in ('vlan100', 'vlan108'):
         print "interface", iface
         print what
1

好吧,有几个错误。首先,Python 的数组是从 0 开始编号的。所以你调用 print internet[1] 是在打印你数组中的第二个元素。你在描述中说“我需要打印列表的第一个项目”,那么你应该用 print internet[0]

其次,你说你需要打印字符串“shutdown”或“no shutdown”,但你实际上打印的是“shut”和“no shut”。把这些打印语句改成“shutdown”和“no shutdown”。

此外,你需要加一些条件判断,来决定是打印“shutdown”还是“no shutdown”;现在你是同时打印了两个。

撰写回答