【问题标题】:"TypeError: len() of unsized object" when using insert for arrays对数组使用插入时出现“TypeError: len() of unsized object”
【发布时间】:2012-01-01 10:54:02
【问题描述】:

目标:在数组中给定索引位置(i)插入一行

使用的语言:python 和 numpy 库

示例:

i=2.0;
a=array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float);
a=insert(a,i,[-1,-1,-1],axis=0);

这给出了错误:TypeError: len() of unsized object

有什么想法吗?

【问题讨论】:

  • 或许您可以告诉我们您使用的是什么语言?这通常通过编辑问题以将语言作为标签之一(现在是“typeerror”)来完成。此外,如果有不止一种常用的实现,您可能想告诉我们您使用的是哪一种。
  • 我找到了解决方案,但堆栈溢出不会让我在 8 小时后才能发布它.. "i=int(2.0)"
  • 2int(2.0) 更有意义,而且 Python 中不需要这些分号。

标签: python numpy typeerror


【解决方案1】:

如果您查看insert 的文档:

>>> help(insert)

你会发现:

Parameters
----------
arr : array_like
    Input array.
obj : int, slice or sequence of ints
    Object that defines the index or indices before which `values` is
    inserted.
values : array_like
    Values to insert into `arr`. If the type of `values` is different
    from that of `arr`, `values` is converted to the type of `arr`.
axis : int, optional
    Axis along which to insert `values`.  If `axis` is None then `arr`
    is flattened first.

看看你所做的,很明显问题在于obj 必须是一个整数、切片或整数序列,而不是浮点数 (i = 2.0)。

如果您设置i=2,您的示例将不会引发错误。我不知道这是否是您想要的,因为您没有说明所需的输出。

【讨论】:

    【解决方案2】:

    我发现了错误。 它给出了错误 i=2.0 is a index and also float 这混淆了 python

    解决方案是将 insert() 的 index 属性类型转换为 int

    按照问题的例子:

    代码:

    i=int(2.0);     # TYPE CASTED AS INT
    
    a=array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float);
    
    a=insert(a,i,[-1,-1,-1],axis=0);
    

    【讨论】:

      【解决方案3】:

      这是要注意 numpy 版本 1.8.1 会隐式转换为 int,因此不会为 OP 的代码引发该错误!

      >>> import numpy as np
      >>> np.__version__
      1.8.1
      

      OP 的代码 -

      >>> i = 2.0;
      >>> a = np.array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float);
      >>> a = np.insert(a,i,[-1,-1,-1],axis=0);
      
      
      >>> a 
      array([[ 1.,  2.,  3.],
             [ 2.,  3.,  4.],
             [-1., -1., -1.],
             [ 3.,  4.,  5.],
             [ 6.,  7.,  8.]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-23
        • 2015-01-20
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2019-01-12
        • 2018-04-25
        • 2021-07-16
        相关资源
        最近更新 更多