【问题标题】:'tuple' object cannot be interpreted as an integer : What is the difference between both codes interpretation'tuple' 对象不能解释为整数:两种代码解释有什么区别
【发布时间】:2020-07-25 19:37:00
【问题描述】:

在这里,我尝试进行 one_hot 编码,首先我使用以下代码:

one_hot = one_hot.reshape((array.shape,n_labels))
print(one_hot)

它给了我以下错误: 元组对象不能被解释为整数,然后我看到其他解决方案,代码将是:

one_hot = one_hot.reshape((*array.shape,n_labels))
print(one_hot)    

并且问题将得到解决,那么两者之间有什么区别,我的意思是当我使用 (*array.shape,n_labels) 而不是 (array.shape,n_lables) 时会发生什么。我很困惑,找不到它。请帮助我!在此先感谢您。

【问题讨论】:

  • 在第二个解压tuple 中,您可以直接访问整数变量。
  • 如果你打印(array.shape,n_labels); print(*array.shape,n_labels) 你会看到不同的

标签: python numpy tuples


【解决方案1】:

* 运算符将列表转换为单个参数。

l = [1, 2, 3]
print(l)

会输出

[1, 2, 3]

但是

print(*l)

会输出

1 2 3

想象一下:没有*的调用将等价于print([1, 2, 3]),第二个调用将等价于print(1, 2, 3)

【讨论】:

    【解决方案2】:

    从数组及其形状开始:

    In [107]: y = np.ones((2,3))                                                                         
    In [108]: y.shape                                                                                    
    Out[108]: (2, 3)
    In [109]: (y.shape,4)                                                                                
    Out[109]: ((2, 3), 4)
    In [110]: (*y.shape,4)                                                                               
    Out[110]: (2, 3, 4)
    

    哪些Out 将在reshape 表达式中起作用?

    回答

    In [111]: np.arange(24).reshape(Out[110])                                                            
    Out[111]: 
    array([[[ 0,  1,  2,  3],
            [ 4,  5,  6,  7],
            [ 8,  9, 10, 11]],
    
           [[12, 13, 14, 15],
            [16, 17, 18, 19],
            [20, 21, 22, 23]]])
    In [112]: np.arange(24).reshape(Out[109])                                                            
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-112-bf548c3c6f2e> in <module>
    ----> 1 np.arange(24).reshape(Out[109])
    
    TypeError: 'tuple' object cannot be interpreted as an integer
    

    这个也可以:

    np.arange(24).reshape(y.shape + (4,)) 
    

    你能找出原因吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2018-03-19
      • 2018-01-19
      • 1970-01-01
      • 2017-08-01
      • 2018-05-15
      相关资源
      最近更新 更多