我是Python新手,并试图学习使用for语句以某种方式显示信息....有没有办法使用for语句来显示这样的列表?
w = "Fa1/1 connected 42 a-full a-100 10/100BaseTX"
v = w.split()
x=v[0]
print "Port ", x
y=v[1]
print "Status ", y
z=v[2]
print "VLAN ", z
a=v[3]
print "Duplex ", a
b=v[4]
print "Speed ", b
c=v[5]
print "Type ", c
-------------------------
Port Fa1/1
Status connected
VLAN 42
Duplex a-full
Speed a-100
Type 10/100BaseTX
我尝试了很多不同的方法,但不断获得价值和索引错误......
感谢您的帮助......
答案 0 :(得分:5)
这样的东西?
>>> w = "Fa1/1 connected 42 a-full a-100 10/100BaseTX"
>>> firstList = ['Port', 'Status', 'VLAN', 'Duplex', 'Speed', 'Type']
>>> testList = zip(firstList, w.split())
>>> for a, b in testList:
print a, b
Port Fa1/1
Status connected
VLAN 42
Duplex a-full
Speed a-100
Type 10/100BaseTX
答案 1 :(得分:2)
你的意思是,像这样?
w = 'Fa1/1 connected 42 a-full a-100 10/100BaseTX'
f = 'Port {0}\nStatus {1}\nVLAN {2}\nDuplex {3}\nSpeed {4}\nType {5}\n'
s = f.format(*w.split())
print s
Port Fa1/1
Status connected
VLAN 42
Duplex a-full
Speed a-100
Type 10/100BaseTX
在这种情况下,使用format string比显式迭代split()
返回的结果更简单。