2012-04-03 57 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