如何序列化一个数组/列表/mat填充了复杂的numb

2024-04-26 05:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想序列化一个用复数填充的ndarray/list,示例代码如下:

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

那么如何处理这个问题呢?在


Tags: inpyjsondefaultencoderreturnislib
3条回答

好吧,让我说清楚

我找到了另一种方法。 使用模块pickle

例如:

fp = open("1.txt","w")
a = [1,2,3]
pickle.dump(a,fp,0)
fp.close()

加载方式相同:

^{pr2}$

只要能找到类,它就可以序列化任何对象

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

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

哪些输出

^{pr2}$

我也需要这个问题的解决方案。我已经写了这段代码,它适用于我需要的任务,但当我运行它检查它并没有完成所有的任务。尽管如此,人们仍然可以使用它。在

# turn complex to str
def replace_complex( inp):
    """Replace complex numbers with strings of 
       complex number + __ in the beginning.

    Parameters:
          
    inp:       input dictionary.
    """

    try:
        if isinstance(inp, complex):
            return "__" + str(inp)
        elif isinstance(inp, list):
            for each in range(len(inp)):
                inp[ each] = replace_complex( inp[ each])
            return inp
        elif isinstance(inp, dict):
            for key,val in inp.items():
                inp[key] = replace_complex( val)
                return inp
        else:
            return inp # nothing found - better than no checks
    except Exception as e:
        print(e)
        return ""

相关问题 更多 >