Python list += iterable 的行为是否记录在任何地方? [英] Is the behaviour of Python's list += iterable documented anywhere?

查看:27
本文介绍了Python list += iterable 的行为是否记录在任何地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,list += x 似乎适用于任何可迭代的 x:

在[6]中:l = []在 [7] 中:l += [1]在 [8] 中:l += (2, 3)在 [9] 中: l += xrange(5)在[10]中:l输出[10]:[1、2、3、0、1、2、3、4]

这种行为是否记录在任何地方?

为了与 list + x 进行对比,后者仅在 x 也是 list 时才有效.这在 文档.

解决方案

来自 Guido van Rossum:p><块引用>

它的工作方式与 .extend() 相同,只是它也返回 self.一世找不到解释这一点的文档.:-(

这里是取自 listobject.c:

list_inplace_concat(PyListObject *self, PyObject *other){PyObject *结果;结果 = 列表扩展(自我,其他);如果(结果 == NULL)返回结果;Py_DECREF(结果);Py_INCREF(自我);返回(PyObject *)自我;}

我已提交错误报告以修复文档:http://bugs.python.org/issue16701

It would appear that in Python, list += x works for any iterable x:

In [6]: l = []

In [7]: l += [1]

In [8]: l += (2, 3)

In [9]: l += xrange(5)

In [10]: l
Out[10]: [1, 2, 3, 0, 1, 2, 3, 4]

Is this behaviour documented anywhere?

To contrast this with list + x, the latter only works if x is also a list. This is spelled out in the documentation.

解决方案

From Guido van Rossum:

It works the same way as .extend() except that it also returns self. I can't find docs explaining this. :-(

Here is the relevant source code taken from listobject.c:

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;
}

I've raised a bug report to have the documentation fixed: http://bugs.python.org/issue16701

这篇关于Python list += iterable 的行为是否记录在任何地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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