2011-03-01 67 views
0

不確定爲什麼上次打印關閉?請參閱徵求意見的具體問題關於python的拆分的簡單問題

john = ['john doe', 44, 32000] 

jane = ['jane doe', 23, 12000] 

people = [john, jane] 

for p in people: 
    #=========================================================================== 
    # p[0] prints "john doe" as expected 
    # p[0].split() prints ['john', 'doe'] as expected 
    # p[0].split()[0] prints "john" and "jane" as expected 
    #=========================================================================== 
    for x in p[0].split(): 
     print('--> ', x[0]) 

    # prints "j","d" - not sure why 
    # expected "john" and "jane" 

回答

4
  1. P [0] .split()返回一個字符串
  2. 的列表中...與列表中的每個字符串造成X
  3. X [0 ]因此是字符串中的第一個字符

你可能想要在'x'後襬脫下標。

+0

OMG,我是一個新人。謝謝。不知道我怎麼會錯過這個 – JAM 2011-03-01 03:33:36

0

正如你所說的使用方法如下

for p in people: 
    #=========================================================================== 
    # p[0] prints "john doe" as expected 
    # p[0].split() prints ['john', 'doe'] as expected 
    # p[0].split()[0] prints "john" and "jane" as expected 
    #=========================================================================== 
    for x in p.split(): 
     print('--> ', x) 
0

,P [0] .split()給你[ '約翰', '美國能源部']。在你的循環中,x依次指向這個列表中的元素,「john」和「doe」。 x [0]表示這些字符中的第一個字符 - 字符串中的第一個字符。