为什么添加到列表中会做不同的事情? [英] Why does adding to a list do different things?

查看:66
本文介绍了为什么添加到列表中会做不同的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> aList = []
>>> aList += 'chicken'
>>> aList
['c', 'h', 'i', 'c', 'k', 'e', 'n']
>>> aList = aList + 'hello'


Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    aList = aList + 'hello'
TypeError: can only concatenate list (not "str") to list

我不明白为什么做list += (something)list = list + (something)会做不同的事情.另外,为什么+=将字符串拆分为要插入列表的字符?

I don't get why doing a list += (something) and list = list + (something) does different things. Also, why does += split the string up into characters to be inserted into the list?

推荐答案

aList += 'chicken'aList.extend('chicken')的python简写. a += ba = a + b之间的区别在于python尝试在调用add之前使用+=调用iadd.这意味着alist += foo将适用于任何可迭代的foo.

aList += 'chicken' is python shorthand for aList.extend('chicken'). The difference between a += b and a = a + b is that python tries to call iadd with += before calling add. This means that alist += foo will work for any iterable foo.

>>> a = []
>>> a += 'asf'
>>> a
['a', 's', 'f']
>>> a += (1, 2)
>>> a
['a', 's', 'f', 1, 2]
>>> d = {3:4}
>>> a += d
>>> a
['a', 's', 'f', 1, 2, 3]
>>> a = a + d
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list

这篇关于为什么添加到列表中会做不同的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆