3

我是 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

我尝试了很多不同的方法,但不断收到价值和索引错误....

谢谢你的帮助....

4

2 回答 2

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
于 2013-07-25T15:43:23.070 回答
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

在这种情况下,使用格式字符串比显式迭代split().

于 2013-07-25T15:45:40.050 回答