如何序列化一个充满复数的 array/list/mat

how to serialize an array/list/mat filled with complex number

我想序列化一个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

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

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

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

输出

["0.006863076166054825+0j"]

好的,让我说清楚

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

例如:

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

加载相同:

fp = open("1.txt")
a = pickle.load(fp)
print a
fp.close()

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

我也需要这个问题的解决方案。我已经编写了这段代码并且它适用于我需要的任务,但是当我 运行 通过检查时它并没有完成所有任务。尽管如此,还是可以使用它。

# 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 ""