在不生成列表的列表的情况下将元素添加到Python列表中

7

我从一个空列表开始,并提示用户输入短语。我想将每个字符作为数组的单个元素添加,但我现在的方法会创建一个嵌套列表。

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']
2个回答

20
< p >如果您想将列表的所有单个元素添加到另一个列表中,请使用 .extend()。不要拓展、提取或迭代.append()的参数。

>>> 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]

3

我认为你处理问题的方式有误。你可以将字符串存储为字符串,然后在必要时逐个字符地迭代它们:

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

输出:

a
b
c

将它们存储为字符列表似乎是不必要的。

你说得对。我可以将它们连接起来,a + b,然后将新字符串视为数组处理。在更大的应用程序中,我正在一个数组中保存需要与这个大字符串的每个字符匹配的对象,因此我认为我需要将每个字符作为单独的数组元素。 - Heitor Chang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接