Python/sage:列表可以从索引1开始吗? [英] Python/sage: can lists start at index 1?

查看:405
本文介绍了Python/sage:列表可以从索引1开始吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个严肃的来源下载了一个鼠尾草脚本.它在我的计算机上不起作用,快速调试后发现问题出在以下事实:在某些时候,作者的行为好像n元素列表的编号是从1到n(而常规"编号)一样在Python中,(因此)贤者为0..n-1).

I've downloaded from a supposedly serious source a sage script. It doesn't work on my computer, and a quick debugging showed that a problem came from the fact that at some point, the authors were doing as if a n-element list was numbered from 1 to n (whereas the "normal" numbering in Python and (thus) sage is 0..n-1).

我想念什么?像APL中一样,隐藏在某个全局变量会改变此约定吗?

What am I missing? Is there a global variable hidden somewhere that changes this convention, like in APL?

感谢您的帮助(尽管我对英语和CSish的理解不够熟练,但我希望我的问题很清楚)

Thanks for your help (I hope my question is clear despite my feeble grasp of both English and CSish...)

推荐答案

Python(因此也包括鼠尾草)列表始终从0开始编号,并且没有办法更改它.

Python (and therefore sage) lists are always numbered from 0, and there isn't a way to change that.

http://hg.python中查看CPython的源代码. 449行上的org/cpython/file/70274d53c1dd/Objects/listobject.c :

static PyObject *
list_item(PyListObject *a, Py_ssize_t i)
{
    if (i < 0 || i >= Py_SIZE(a)) {
        if (indexerr == NULL) {
            indexerr = PyString_FromString(
                "list index out of range");
            if (indexerr == NULL)
                return NULL;
        }
        PyErr_SetObject(PyExc_IndexError, indexerr);
        return NULL;
    }
    Py_INCREF(a->ob_item[i]);
    return a->ob_item[i];
}

项目查找将直接委派给基础C数组,并且 C数组始终为零, .因此,Python列表也始终基于零.

The item lookup delegates straight to the underlying C array, and C arrays are always zero-based. So Python lists are always zero-based as well.

这篇关于Python/sage:列表可以从索引1开始吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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