python - 在超出范围的索引处插入列表 - 行为类似于追加

标签 python python-2.7

我有一个 list

 a = [1, 2, 3]

当我这样做时

a.insert(100, 100)

[1, 2, 3, 100]

由于 list 最初的大小为 4,而我试图在索引 100 处插入值,它的行为就像 append 而不是抛出任何错误,因为我试图插入一个甚至不存在的索引。

应该不会扔

IndexError: list assignment index out of range

当它抛出异常时 我尝试做

a[100] = 100

问题: 1. 知道为什么它被设计成静默处理而不是通知用户异常?

个人意见:

让我们看看其他语言在这种情况下的表现:

鲁比:

    > a = [1, 2]
    > a[100] = 100
    > a
 => [1, 2, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 100] 

ruby 处理这个问题的方式非常清晰,至少对我来说听起来很有意义。

Java:

在 java 中,方法 .add(index, value) 如果应用超出范围的索引(例如在 arraylist 上,linkedlist 上)将抛出 java.lang.IndexOutOfBoundsException .

所以我觉得要么它应该抛出异常(就像 java 那样),要么在两者之间的范围内插入 null (因为 ruby​​ 处理它)。 但是在 python 中这种无声的处理方式实在是让人摸不着头脑。

更新(2014 年 9 月 16 日 IST 上午 8:30):

根据其中一位回答者的建议,我在 python-dev 中发布了这个问题,并得到了回复。可以看这个python dev mailing list thread .如果您发现话题链接发生了变化,您可以通过 google search 找到答案。以python dev开头的问题标题。

最佳答案

来自 docs :

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

所以从技术上讲,当您执行 a.insert(100, 100) 时,它确保 100 将插入到 before 的索引处100 在这种情况下恰好是索引 3。

此外,我们可以看看 the implementation :

static int
ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
{
    Py_ssize_t i, n = Py_SIZE(self);
    PyObject **items;
    if (v == NULL) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (n == PY_SSIZE_T_MAX) {
        PyErr_SetString(PyExc_OverflowError,
            "cannot add more objects to list");
        return -1;
    }

    if (list_resize(self, n+1) == -1)
        return -1;

    if (where < 0) {
        where += n;
        if (where < 0)
            where = 0;
    }
    if (where > n)  // <-- Here the implementation handles indexes > list-len
        where = n;
    items = self->ob_item;
    for (i = n; --i >= where; )
        items[i+1] = items[i];
    Py_INCREF(v);
    items[where] = v;
    return 0;
}

关于python - 在超出范围的索引处插入列表 - 行为类似于追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25840177/

相关文章:

Python igraph : delete vertices from a graph

python - PySpark:从随机均匀分布创建数据框

Python 日志记录 : Flask + uWsgi + nginx

python - 不使用循环计算numpy中多个多项式的根

python - python中的牌组卡类

python - 并行运行多个子进程,在屏幕上显示所有输出,直到完成

python - QtCore Signal 可以设置为当前类吗?

python - 在 Visual Studio 中使用 PTVS 调试 Python 代码时出现控制台窗口

python - 从版本 2.7 运行 python 版本 2.5 api

python - 如何在其派生类中覆盖列表的切片功能