2012-04-03 82 views
3

我從一個空列表開始,並提示用戶輸入一個短語。我想將每個字符添加爲數組的單個元素,但是我這樣做的方式會創建一個列表的列表。追加到Python列表而不使列表清單

myList = [] 
for i in range(3): 
    myPhrase = input("Enter some words: ") 
    myList.append(list(myPhrase)) 
    print(myList) 

我得到:

Enter some words: hi bob 
[['h', 'i', ' ', 'b', 'o', 'b']] 

Enter some words: ok 
[['h', 'i', ' ', 'b', 'o', 'b'], ['o', 'k']] 

Enter some words: bye 
[['h', 'i', ' ', 'b', 'o', 'b'], ['o', 'k'], ['b', 'y', 'e']] 

但結果我想要的是:

['h', 'i', ' ', 'b' ... 'o', 'k', 'b', 'y', 'e'] 

回答

8

.append()參數不擴大,提取,或以任何方式遍歷。如果要將列表中的所有單個元素添加到另一個列表,則應該使用.extend()

>>> L = [1, 2, 3, 4] 
>>> M = [5, 6, 7, 8, 9] 
>>> L.append(M) # Takes the list M as a whole object 
>>>    # and puts it at the end of L 
>>> L 
[0, 1, 2, 3, [5, 6, 7, 8, 9]] 
>>> L = [1, 2, 3, 4] 
>>> L.extend(M) # Takes each element of M and adds 
>>>    # them one by one to the end of L 
>>> L 
[0, 1, 2, 3, 5, 6, 7, 8, 9] 
+0

是的,這是我一直在尋找,謝謝! :) – 2012-04-03 18:22:47

3

我想你會以錯誤的方式解決問題。您可以將您的字符串爲字符串,然後對它們進行迭代後,一個字符時間爲必要的:

foo = 'abc' 
for ch in foo: 
    print ch 

輸出:

a 
b 
c 

存儲它們作爲一組字符似乎沒有必要。

+0

你說得對。我可以將它們連接起來,a + b,然後將新字符串視爲數組。在更大的應用程序中,我將數組中的對象放在需要匹配這個大字符串的每個字符的數組中,所以我認爲我需要將每個字符作爲數組中的一個單獨的東西。 – 2012-04-03 18:21:45