将自定义类转换为标准Python类型

时间:2015-07-23 16:32:14

标签: python numpy casting

我正在使用名为numpy的{​​{1}}数组。我正在玩下面的代码:

predictions

输出结果为:

print type(predictions)
print list(predictions)

我想知道<type 'numpy.ndarray'>` [u'yes', u'no', u'yes', u'yes', u'yes'] 如何设法建立他们的numpy类,以便它可以转换为不使用自己的ndarray函数的列表,而是使用标准的Python函数。

Python版本:2.7,Numpy版本:1.9.2

2 个答案:

答案 0 :(得分:2)

  

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

documentationlist的参数定义为iterable; new_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

答案 1 :(得分: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,另一个是{{1包含在str类中。最近关于序列化数组的问题出现了这种区别。

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

arr

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)是嵌套列表。

Python Pandas: use native types

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

相关问题