为什么json.dumps(np.arange(5).tolist())工作时json.dumps(list(np.arange(5)))失败 [英] Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works

查看:128
本文介绍了为什么json.dumps(np.arange(5).tolist())工作时json.dumps(list(np.arange(5)))失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当最近更新了运行Ubuntu的计算机并将Python的默认版本更改为2.7时,我注意到了这个问题.

I noticed this problem when a computer running Ubuntu was updated recently and the default version of Python changed to 2.7.

import json
import numpy as np

json.dumps(list(np.arange(5))) # Fails, throws a "TypeError: 0 is not JSON serializable"
json.dumps(np.arange(5).tolist()) # Works 

numpy数组的list()和tolist()方法之间有区别吗?

Is there a difference between list() and the tolist() methd of a numpy array?

推荐答案

看来tolist()方法将numpy int32(或任何大小)转换回int,JSON知道该如何处理.与:

It looks like the tolist() method turns the numpy int32 (or whatever size you have) back into an int, which JSON knows what to do with:

>>> list(np.arange(5))
[0, 1, 2, 3, 4]
>>> type(list(np.arange(5)))
<type 'list'>
>>> type(list(np.arange(5))[0])
<type 'numpy.int32'>
>>> np.arange(5).tolist()
[0, 1, 2, 3, 4]
>>> type(np.arange(5).tolist())
<type 'list'>
>>> type(np.arange(5).tolist()[0])
<type 'int'>

正如文档中对tolist()所说的那样:

As the docs say for tolist():

将数组作为(可能是嵌套的)列表返回.

Return the array as a (possibly nested) list.

将数组数据的副本作为(嵌套的)Python列表返回. 数据项 会转换为最接近的兼容Python类型.

Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible Python type.

最后一行在这里有所不同.

The last line makes the difference here.

这篇关于为什么json.dumps(np.arange(5).tolist())工作时json.dumps(list(np.arange(5)))失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆