gpt4 book ai didi

python - 如果乘以负值,列表或元组如何变为空?

转载 作者:行者123 更新时间:2023-11-28 21:31:26 25 4
gpt4 key购买 nike

如果乘以负值,列表或元组如何变为空?

例如:

>>> b = [1,2,3] * 2
>>> b
[1, 2, 3, 1, 2, 3]
>>> c = [1,2,3] * -1
>>> c
[]
>>> d = [1,2,3] * -2
>>> d
[]

最佳答案

文档

正如人们在我之前回答的那样,documentation 中定义的 Python 标准行为:

In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.


源代码

如果你想知道为什么会这样,你可以关注 CPython 的源代码:

abstract.c中的代码开始:

PyObject *
PyNumber_Multiply(PyObject *v, PyObject *w)
{
PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
...
if (mv && mv->sq_repeat) {
return sequence_repeat(mv->sq_repeat, v, w);
}
else if (mw && mw->sq_repeat) {
return sequence_repeat(mw->sq_repeat, w, v);
}
...
}

然后,在 listobject.c 上:

static PySequenceMethods list_as_sequence = {
...
(ssizeargfunc)list_repeat, /* sq_repeat */
...
}

跳转到list_repeat :

static PyObject *
list_repeat(PyListObject *a, Py_ssize_t n)
{
...
if (n < 0)
n = 0;
...
if (size == 0)
return PyList_New(0);
...
}

关于python - 如果乘以负值,列表或元组如何变为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58097771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com