为什么单索引numpy数组形式的额外逗号 [英] why an extra comma in the shape of a single index numpy array
问题描述
一个numpy数组 a = numpy.arange(12)
A numpy array a a = numpy.arange(12)
具有形状 a.shape =(12,)
has shape a.shape = (12,)
我们为什么需要逗号?形状(12)是否保留用于其他用途?
Why do we need the comma? is shape (12) reserved for something else?
推荐答案
我们不对单元素元组使用(12)
的原因(例如对单元素列表使用[12]
)是因为还会出现圆括号.在公式中.例如,在x = 2*(5+7)
中,部分(5+7)
只是一个数字,而不是一个元组.但是,如果我们实际上将其表示为一个元素元组怎么办?尾部逗号是一种指示方式.比较:
The reason we don't use (12)
for a one-element tuple (like [12]
for one-element list) is that round parentheses also appear in formulas. E.g., in x = 2*(5+7)
the part (5+7)
is just a number, not a tuple. But what if we actually meant it to be a one-element tuple? The trailing comma is a way to indicate that. Compare:
>>> 2*(5+7)
24
>>> 2*(5+7,)
(12, 12)
对于列表,不需要尾部逗号,尽管某些样式指南建议使用逗号以保持一致性.
With lists, the trailing comma is not needed although some style guides recommend it for consistency.
>>> 2*[5+7]
[12, 12]
>>> 2*[5+7,]
[12, 12]
这篇关于为什么单索引numpy数组形式的额外逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!