【问题标题】:What is difference between (1,2,3) vs [1,2,3] in python ?python 中 (1,2,3) 与 [1,2,3] 有什么区别?
【发布时间】:2018-06-24 17:47:46
【问题描述】:

在以下代码中,大小和随机数的形状仅相同,一维数组(3,) 那为什么 size=(3, 3, 2) & randm=[-1.10343097 -1.31819984 0.20597956]

Q.1 为什么不同的括号 () 与 [] Q.2 每个括号 () 和 [] 的意义是什么

 image = np.array([[[ 0.67826139,  0.29380381],
        [ 0.90714982,  0.52835647],
        [ 0.4215251 ,  0.45017551]],

       [[ 0.92814219,  0.96677647],
        [ 0.85304703,  0.52351845],
        [ 0.19981397,  0.27417313]],

       [[ 0.60659855,  0.00533165],
        [ 0.10820313,  0.49978937],
        [ 0.34144279,  0.94630077]]])

size = np.shape(image)
print (str (size))
print (np.shape(size))

randm = np.random.randn(3)
print (randm)
print (np.shape(randm)) 

输出-

(3, 3, 2)
(3,)
[-1.10343097 -1.31819984  0.20597956]
(3,)

【问题讨论】:

标签: python numpy


【解决方案1】:

image 是一个多维 numpy 数组。它是通过列表的嵌套列表(括号和逗号)定义的。

image.shape 是一个元组,因此显示为 ()。

其他答案,以及假设的重复,关注 Python 对列表和元组的区别。但这需要一个专注于 numpy 的答案。

一个简单的 3d 数组:

In [244]: x = np.array([[[1,2],[3,4]]])
In [245]: x
Out[245]: 
array([[[1, 2],
        [3, 4]]])

您可以将形状作为属性获取,也可以通过函数调用获取

In [246]: x.shape
Out[246]: (1, 2, 2)
In [247]: np.shape(x)
Out[247]: (1, 2, 2)

shape 本身没有形状属性。 len(x.shape) 可以工作,因为它是一个元组。

In [248]: (x.shape).shape
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-248-b00338a7f4bf> in <module>()
----> 1 (x.shape).shape

AttributeError: 'tuple' object has no attribute 'shape'

np.shape(...shape) 令人困惑。 np.shape() 将首先将其输入转换为一个数组(如果还没有的话)并返回它的形状:

In [249]: np.shape(x.shape)
Out[249]: (3,)

所以我通常不会采用这种形状的形状。然而,它确实表明了一个关键点。 (3,) 是一个 1 元素元组。 , 很重要。 0d 数组的形状元组是()

下一部分创建一个 3 元素数组

In [250]: np.random.randn(3)
Out[250]: array([ 2.06265058,  0.87906775, -0.96525837])
In [251]: _.shape
Out[251]: (3,)
In [252]: print(__)
[ 2.06265058  0.87906775 -0.96525837]

同样,一个 (3,) 形状的元组。数组的str 显示使用方括号,但省略了逗号。这有助于将其与常规列表区分开来。

(还有一个数组类型用 () 显示,一个结构化数组。但这是一个更高级的话题。)

【讨论】:

    【解决方案2】:
    (1,2,3) -Tuple
    [1,2,3] -List
    

    阅读本文了解更多关于tuple and list的信息

    【讨论】:

    • @user2864740 np.shape 返回一个元组。
    • 问题问 (1,2,3) 和 [1,2,3] 有什么区别所以 (1,2,3) 是元组和 [1,2,3] 列表。
    • @PM2Ring 当然,但我可以将 FooBaz 的输出更改为看起来相同:}
    • 只是说这么短的答案还有很多不足之处。
    【解决方案3】:

    () 表示法表示数据类型为tuple,而[] 表示list

    此外,元组使用更少的内存并且是不可变的,而列表是可变的。

    【讨论】:

    • 在我意识到我的意思是tuple后我改变了它
    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 2010-09-05
    • 2014-07-14
    • 2014-07-13
    • 1970-01-01
    • 2014-10-10
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多