如何序列化填充有复数的数组/列表/垫 [英] how to serialize an array/list/mat filled with complex number

查看:114
本文介绍了如何序列化填充有复数的数组/列表/垫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要序列化一个用复数填充的ndarray/列表,示例代码在这里:

I want to serialize an ndarray/list filled with complex number, the example code is here:

a = [None]
a[0] =  0.006863076166054825+0j
a
[(0.006863076166054825+0j)]
>>> b = json.dumps(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python27\lib\json\__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "D:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "D:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: (0.006863076166054825+0j) is not JSON serializable

那该如何处理呢?

推荐答案

json.dumps(a)将失败,因为该函数在尝试解释复数时无法处理该复数.传递值的唯一可能性是作为字符串:

The json.dumps(a) will fail, because the function can not handle the complex number when it tries to interpret it. The only possibility to pass the value is as string:

a = [1]
a[0] = "0.006863076166054825+0j"
b = json.dumps(a)
print b

输出

["0.006863076166054825+0j"]

这篇关于如何序列化填充有复数的数组/列表/垫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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