【发布时间】:2019-01-05 18:49:52
【问题描述】:
我在 Jupyter Notebook 中运行了以下代码:
list_1 = []
list_1 += "cat"
print(list_1)
得到以下输出:
['c', 'a', 't']
但是当我运行这个时:
list_1 = []
list_1 = list_1 + "cat"
print(list_1)
它给出了以下错误:
TypeError: can only concatenate list (not "str") to list
我没能理解这两种方法,一个字符串被添加到一个列表中。
是因为 '+=' 符号还是与列表和字符串的串联相关的问题导致了该错误?
【问题讨论】:
-
有一个excellent answer on the difference between + and +=。除此之外,请注意 Python 尝试将“cat”解释为一个列表,默认为单个字符的列表。
-
我确实检查了那个答案。我感兴趣的问题是将字符串连接到列表,但该答案仅解决了
+=符号如何影响两个列表的连接。当您清除 Python 将“猫”视为字符列表时,我能够完全理解这个问题。谢谢
标签: python python-3.x list concatenation