python *运算符,使用默认值创建列表 [英] python * operator, creating list with default value
问题描述
以下工作如何?
>>> 3*[2]
>>> [2,2,2]
>>> [2]*3
>>> [2,2,2]
我知道*
是位置扩展运算符.由于[2]
是一个包含单个项目的列表,所以我看不到3*[2]
如何扩展到任何有意义的内容,我希望使用SyntaxError
,但事实并非如此.
I understand that *
is the positional expansion operator. Since [2]
is a list with a single item, I don't see how 3*[2]
expands to anything meaningful, I'd expect a SyntaxError
, but that's not the case.
我很难找到一个现有的答案,我发现所有引用*args
和**kwargs
来传递可变参数列表,但这并不能完全回答我的问题.
I'm having a hard time searching for an existing answer, all I find are references to *args
and **kwargs
for passing variadic parameter lists, which don't quite answer my question.
推荐答案
*
是 序列类型文档:
*
is the multiplication operator. All Python sequences support multiplication. See the Sequence Types documentation:
s * n
,n * s
s 级联的
s * n
,n * s
n shallow copies of s concatenated
请注意,副本是 shallow ;任何嵌套的可变类型也不会递归地复制.这可能会导致令人惊讶的结果:
Note that the copies are shallow; any nested mutable types are not recursively copied too. This can lead to suprising results:
>>> nested = [[None]] * 5
>>> nested
[[None], [None], [None], [None], [None]]
>>> nested[0].append(42)
>>> nested
[[None, 42], [None, 42], [None, 42], [None, 42], [None, 42]]
只有一个嵌套的[None]
列表,被引用5次,而不是5个单独的列表对象.
There is just one nested [None]
list, referenced 5 times, not 5 separate list objects.
*args
和**kw
变量参数语法仅在函数定义或调用中具有含义(因此callable_object(<arguments>)
).它根本不适用于这里.参见 **(双星)和*(星号)用于参数?有关该语法的更多详细信息.
The *args
and **kw
variable argument syntax only has meaning in a function definition or in a call (so callable_object(<arguments>)
). It doesn't apply here at all. See What does ** (double star) and * (star) do for parameters? for more detail on that syntax.
序列类型通过 object.__mul__()
重载*
运算符和 object.__rmul__()
方法(表达式中的左或右操作数),请参见 模拟容器类型 ,以获取有关钩子序列类型通常实现的文档.
Sequence types overload the *
operator through the object.__mul__()
and object.__rmul__()
methods (when being the left or right operand in the expression), see Emulating container types for documentation on what hooks sequence types typically implement.
这篇关于python *运算符,使用默认值创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!