如果x是列表,为什么x + ="ha"? x = x +"ha"表示引发异常? [英] If x is list, why does x += "ha" work, while x = x + "ha" throws an exception?

查看:127
本文介绍了如果x是列表,为什么x + ="ha"? x = x +"ha"表示引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,+ op for list仅要求第二个操作数是可迭代的,而"ha"显然是可迭代的.

From what little I know, + op for lists only requires the 2nd operand to be iterable, which "ha" clearly is.

在代码中:

>>> x = []
>>> x += "ha"
>>> x
['h', 'a']
>>> x = x + "ha"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

推荐答案

+=与列表一起使用就像调用extend,而不是+.

Using += with a list is like calling extend, not +.

  • 您可以通过迭代方式调用extend.
  • 您只能将+与其他列表一起使用.
  • You can call extend with an iterable.
  • You can only use + with another list.

我只能猜测为什么要做出此决定,但我想这是出于性能原因.调用+会创建一个新对象并复制所有项目,而extend可以使用现有列表对象中的可用空间来保存副本(在某些情况下).

I can only guess why this decision was made, but I imagine it is for performance reasons. Calling + results in a new object being created and all items being copied, whereas extend can use free space in the existing list object saving a copy in some cases.

此决定的另一个副作用是,如果您将x += y写入列表,其他引用将看到更改,但如果使用x = x + y,则不会.如下所示:

Another side-effect of this decision is that if you write x += y other references to the list will see the change but if you use x = x + y then they will not. This is demonstrated below:


>>> x = ['a','b']
>>> y = ['c', d']
>>> z = x
>>> x += y
>>> z
['a', 'b', 'c', 'd']

>>> x = ['a','b']
>>> y = ['c', d']
>>> z = x
>>> x = x + y
>>> z
['a', 'b']

参考

列表的Python源代码.

+=的源代码:


static PyObject *
list_inplace_concat(PyListObject *self, PyObject *other)
{
    PyObject *result;

    result = listextend(self, other);
    if (result == NULL)
        return result;
    Py_DECREF(result);
    Py_INCREF(self);
    return (PyObject *)self;
}

+的源代码:


static PyObject *
list_concat(PyListObject *a, PyObject *bb)
{
    Py_ssize_t size;
    Py_ssize_t i;
    PyObject **src, **dest;
    PyListObject *np;
    if (!PyList_Check(bb)) {
        PyErr_Format(PyExc_TypeError,
                  "can only concatenate list (not \"%.200s\") to list",
                  bb->ob_type->tp_name);
        return NULL;
    }

    // etc ...

这篇关于如果x是列表,为什么x + ="ha"? x = x +"ha"表示引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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