【问题标题】:Please specify what is the difference of these two line in python请说明这两行在python中有什么区别
【发布时间】:2023-01-19 23:48:44
【问题描述】:
宣言
lst = []
string = 'a'
python中这两行有什么区别为什么第一行有效而另一行无效
lst += 'a' # this line is working
lst = lst + 'a' # but this line is showing error 'can only concatenate list (not "str") to list'
不明白为什么这两个陈述给出不同的结果
【问题讨论】:
标签:
python
python-3.x
list
compiler-errors
【解决方案1】:
在列表中 += 与 extend 相同。该参数被视为可迭代的。所以它迭代字符串并添加它。但这在一般情况下是不正确的,例如长度 > 1 的字符串。
>>> lst = []
>>> lst += "ab"
>>> lst
['a', 'b'] # not what is expected probably
或添加一个整数
>>> lst += 0
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not iterable
申请+时,正确的词应该是一个列表。
在你的情况下,最好的解决方案是
lst += ['a']
或者
lst.append('a')
这避免了创建一个列表只是为了将它添加到第一个。
作为旁注,
lst = lst + other_list
是不同的从
lst += other_list
因为它在添加了 other_list 的旧列表副本上重新分配了 lst 名称。
- 最好注意,如果其他变量仍在引用旧的
lst
- 另外,旧内容的复制会影响性能。
【解决方案2】:
所以你在这里添加变量 a,而不是字符串 'a':
lst += a
我不知道 a 中存储了哪个值,或者这是错字?请澄清。