将 Python 中 table 个数字的列表保存为 Mathematica 易于阅读的格式?

Save list of table of numbers from Python into format easily readable by Mathematica?

我是运行中的模拟Python。模拟的结果总结在数字矩阵列表中。有没有一个很好的导出格式可以用来编写这个列表,以便以后我可以轻松地在 Mathematica 中读取文件,Mathematica 会自动将其识别为矩阵列表?

好吧,这取决于您的矩阵有多大,以及您关心的是速度还是内存。最简单的解决方案是自己创建一个 plain-text Mathematica 表达式。只需遍历您的矩阵并在 Mathematica formate 中创建它们的列表。这归结为在文件中写入大括号和数字

{mat1, mat2, ...}

其中 mat1 等本身就是数字列表的列表。

更新 1

如果你想要一个标准化的格式,那么你可以很容易地看一下 import into Mathematica. One thing that hits the eye (after it was hit by MTX, which obviously doesn't work) is the MAT format. A quick search seems to indicate, that you can write those files with Python

更新 2

关于您的评论

Pythonica looks nice. Regrettably, I am running the Python simulations on a cluster that does not have Mathematica installed. I am using Mathematica in my personal PC for post-processing.

好吧,但是这个包连500行代码都不到。你为什么不浏览它并取出你需要的东西:将任意 Python 列表转换为 Mathematica 代码

的代码
_id_to_mathematica = lambda x: str(x)


def _float_to_mathematica(x):
    return ("%e" % x).replace('e', '*10^')


def _complex_to_mathematica(z):
    return 'Complex' + ('[%e,%e]' % (z.real, z.imag)).replace('e', '*10^')


def _str_to_mathematica(s):
    return '\"%s\"' % s


def _iter_to_mathematica(xs):
    s = '{'
    for x in xs:
        s += _python_mathematica[type(x)](x)
        s += ','
    s = s[:-1]
    s += '}'
    return s


_python_mathematica = {bool: _id_to_mathematica,
                       type(None): _id_to_mathematica,
                       int: _id_to_mathematica,
                       float: _float_to_mathematica,
                       long: _id_to_mathematica,
                       complex: _complex_to_mathematica,
                       iter: _iter_to_mathematica,
                       list: _iter_to_mathematica,
                       set: _iter_to_mathematica,
                       xrange: _iter_to_mathematica,
                       str: _str_to_mathematica,
                       tuple: _iter_to_mathematica,
                       frozenset: _iter_to_mathematica}

l = [[1, 2, 3], 1, [1, 5, [7, 3, 7, 8]]]
print(_iter_to_mathematica(l))

输出是一个字符串

{{1,2,3},1,{1,5,{7,3,7,8}}}

您可以直接保存到文件中并使用 Get.

将其加载到 Mathematica

矩阵有多大?

如果不是太大,JSON 格式会很好。我用过这个,在 Python 和 Mathematica 中都很容易使用。

如果它们很大,我会尝试 HDF5。我没有从 Python 写这个的经验,但我知道它可以存储多个数据集,因此它可以存储多个不同大小的矩阵。