【问题标题】:Convert custom class to standard Python type将自定义类转换为标准 Python 类型
【发布时间】:2015-07-23 16:32:13
【问题描述】:

我正在使用一个名为 predictionsnumpy 数组。我正在玩以下代码:

print type(predictions)
print list(predictions)

输出是:

<type 'numpy.ndarray'>`
[u'yes', u'no', u'yes', u'yes', u'yes']

我想知道numpy 是如何设法构建他们的ndarray 类的,以便可以将其转换为一个列表,而不是使用他们自己的list 函数,而是使用标准的Python 函数。

Python 版本:2.7,Numpy 版本:1.9.2

【问题讨论】:

  • 请注意,如果实现了whatever.__iter__list(whatever) 将起作用 - 即 Python 将使用迭代器并将每个结果对象放入列表中。

标签: python numpy casting


【解决方案1】:

下面我是从纯Python的角度回答的,但是numpy的 数组实际上是用 C 实现的 - 参见例如the array_iter function.

documentationlist 的参数定义为iterablenew_list = list(something) 有点像:

new_list = []
for element in something:
    new_list.append(element)

(或者,在列表理解中:new_list = [element for element in something])。因此,要为自定义类实现此行为,您需要定义__iter__ magic method

>>> class Demo(object):
    def __iter__(self):
        return iter((1, 2, 3))


>>> list(Demo())
[1, 2, 3]

请注意,转换为其他类型需要different methods

【讨论】:

    【解决方案2】:

    正如其他人所写,list() 之所以有效,是因为数组是可迭代的。它相当于[i for i in arr]。要理解它,您需要了解数组上的迭代是如何工作的。特别是list(arr)arr.tolist() 不同。

    In [685]: arr=np.array('one two three four'.split())
    
    In [686]: arr
    Out[686]: 
    array(['one', 'two', 'three', 'four'], 
          dtype='<U5')
    
    In [687]: ll=list(arr)
    
    In [688]: ll
    Out[688]: ['one', 'two', 'three', 'four']
    
    In [689]: type(ll[0])
    Out[689]: numpy.str_
    
    In [690]: ll1=arr.tolist()
    
    In [691]: ll1
    Out[691]: ['one', 'two', 'three', 'four']
    
    In [692]: type(ll1[0])
    Out[692]: str
    

    llll1 的打印显示看起来一样,但元素的type 不同,一个是str,另一个是包裹在numpy 类中的str。这种区别出现在最近关于序列化数组的问题中。

    arr 为 2d 时,区别变得更加明显。然后简单的交互产生行,而不是元素:

    In [693]: arr=np.reshape(arr,(2,2))
    
    In [694]: arr
    Out[694]: 
    array([['one', 'two'],
           ['three', 'four']], 
          dtype='<U5')
    
    In [695]: list(arr)
    Out[695]: 
    [array(['one', 'two'], 
           dtype='<U5'), array(['three', 'four'], 
           dtype='<U5')]
    
    In [696]: arr.tolist()
    Out[696]: [['one', 'two'], ['three', 'four']]
    

    list(arr) 现在是两个数组,而arr.tolist() 是一个嵌套列表。

    Python Pandas: use native types

    Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多