4
$\begingroup$

I was wondering if you know, how to save a Mathematica list (variable) such that it can be read later in Python.

In order words, how to save a variable

var={{1,{1,0}},{2,{0,0,0}},{3,{2,3}},{4,{4,5,6}},{5,{7,8,9}}}

to be used by Python?

Thank you.

$\endgroup$
  • 3
    $\begingroup$ Aren't Python lists just like Mathematica lists but with [, ] instead of {, }? Have you tried StringReplace[ToString@var, {"{"->"[","}"->"]"}]? $\endgroup$ – C. E. Jan 13 '15 at 14:37
  • $\begingroup$ See mathematica.stackexchange.com/questions/120790/… $\endgroup$ – ffc Jun 7 '17 at 10:39
5
$\begingroup$
ExportString[var, "RawJSON", "Compact" -> True]

[[1,[1,0]],[2,[0,0,0]],[3,[2,3]],[4,[4,5,6]],[5,[7,8,9]]]


Update

And note the 11.2 coming up have a built-in method to do this

$\endgroup$
4
$\begingroup$

You should use standard ways to transfer data as e.g CSV-files.

Hence, just use Export["file.csv",var] in Mathematica to export the file

For reading csv-files with python, see tutorials as: http://pymotw.com/2/csv/

You can also use this format with spreadsheets as LibreOffice Calc or MS Excel

$\endgroup$
2
$\begingroup$

Standard Method

To safely and automatically transfer large data, you should do as Phillipp mentioned, by using the following:

Export["myListFile.csv", myList]

Quick Method

However, (as also mentioned by C.E. in the comment above), if you want to do this manually via copy and paste, you can define the following function for yourself. Just feed it your Mathematica list and it will automatically copy its Python format to your clipboard.

pyList[myList_] := 
 CopyToClipboard@
  StringReplace[
   ToString@InputForm@myList, {"}, {" -> "],\n [", "{" -> "[", 
    "," -> ",", "}" -> "]"}]

Details

Here, we are replacing { with [, } with ]. Everytime a sublist ends and a new one begins we create a new line via "}, {" -> "],\n [" and this must be placed as the first pattern. "," -> "," is for generalization purposes, i.e. gives you the option to have or remove spacing after ,. If you are wondering, the InputForm will preserve lists such as {"a", 1, "2", 3} and if removed, the result will be {a, 1, 2, 3}, i.e. strings/characters will be replaced by "meaningful" expressions and will cause computation and syntax error. I would avoid running this on extremely large lists which above a few thousand elements.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.