[英]creating list with * operator in python
Why does [0] * 5
create a list [0, 0, 0, 0, 0]
, rather than [[0], [0], [0], [0], [0]]
?为什么
[0] * 5
创建一个列表[0, 0, 0, 0, 0]
而不是[[0], [0], [0], [0], [0]]
?
Doesn't the *
operator duplicate [0]
5 times resulting in [[0], [0], [0], [0], [0]]
? *
运算符不会重复[0]
5 次导致[[0], [0], [0], [0], [0]]
吗?
Just like math:就像数学一样:
[0] * 5 = [0] + [0] + [0] + [0] + [0]
, which is [0, 0, 0, 0, 0]
. [0] * 5 = [0] + [0] + [0] + [0] + [0]
,即[0, 0, 0, 0, 0]
。
I think people would be more surprised if [0] + [0]
suddenly became [[0], [0]]
.我认为如果
[0] + [0]
突然变成[[0], [0]]
人们会更加惊讶。
For strings, tuples, and lists, +
is an append operator.对于字符串、元组和列表,
+
是附加运算符。 This multiplication holds true for all of them.这种乘法适用于所有人。
阅读序列类型的 Python 文档似乎是因为[0] * 5
是[0] + [0] + [0] + [0] + [0]
的简写(就像乘法在数学中是加法;当“乘”列表时,它的工作原理相同)。
不,它将元素相乘并且 [0] 列表(就像数学集一样)有一个元素 0,而不是 [[0]]。
Use statement below to create [[0], [0], [0], [0], [0]]:使用下面的语句创建 [[0], [0], [0], [0], [0]]:
[[0]*1]*5
Note that the list you've mentioned above is a 2d list, so you must use * operator in right way.请注意,您上面提到的列表是二维列表,因此您必须正确使用 * 运算符。 It means your list has 5 rows and 1 column.
这意味着您的列表有 5 行和 1 列。
Below is the real result: enter image description here以下是实际结果:在此处输入图像描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.