【问题标题】:Concatenation of a string to a list [duplicate]将字符串连接到列表[重复]
【发布时间】: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


【解决方案1】:

list_1 += "cat" 正在调用list_1.__iadd__,它在内部使用list_1.extend("cat"),并将可迭代"cat" 中的每个字符一个接一个地附加到列表中。

list_1 + "cat" 尝试调用 list_1.__add__ 并且您注意到此方法失败,因为它需要两个列表。

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 2015-09-11
    相关资源
    最近更新 更多