2014-06-15 50 views
0

我寫此塊:列表操作錯誤輸出

stst = "Hello [email protected]#" 

empt = [] 

def shplit(stst): 
    tst = stst.split() 
    print tst 
    for i in tst: 
     empt = list(i) 
    print empt 


shplit(stst) 

我從打印得到的是:

['Hello', '[email protected]#'] 
['W', 'o', 'r', 'l', 'd', '!', '@', '#'] 

我想不通,爲什麼單詞「你好」不會出現完全在第二個列表中。 這是怎麼發生的?

+0

用你自己的話說,爲什麼*應該*它附上AR?逐步瀏覽它,並解釋你在每一步都會遇到'empt'。 –

回答

1

你的縮進不正確:

for i in tst: 
    empt = list(i) 
print empt # this happens after the loop 

當你print empt,循環完成,所以你只能從循環的最後一次迭代中看到價值。如果你想看到所有迭代,縮進print一層:

for i in tst: 
    empt = list(i) 
    print empt # this happens inside the loop 

另外,如果你想填補empt與所有的各種i S的,使用list.extend

for i in tst: 
    empt.extend(i) 
print empt 

這給出了:

>>> shplit(stst) 
['Hello', '[email protected]#'] 
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '!', '@', '#'] 
+0

嗨,你寫的最後一塊是我正在尋找的。你能解釋清單和擴展函數之間的區別嗎?感謝\ – user3091216

+0

爲什麼不閱讀文檔 - ['list'](https://docs.python.org/2/library/functions.html#list),['list.extend'](https:// docs。 python.org/2/library/stdtypes.html#mutable-sequence-types)。你所有的代碼每次都會用新列表覆蓋'empt'。 – jonrsharpe