Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer list from Python to Julia?

Tags:

python

julia

In Python I created a 3d list of data which I want to have access to in Julia. I wonder how to do that conveniently. If doing by writing in text file, how to parse it from julia? Or maybe there are specialized solutions for that, such as feather for dataframes?

For example, in python:

a = [[[0, 1]], [[1, 0.5], [2, 0.5]]]
save_to_convenient_for_parsing_file(a, filename)

in julia:

a = read_from_convenient_for_parsing_file(filename)
a
>2-element Vector{Vector{Vector{Float64}}}:
 [[0.0, 1.0]]
 [[1.0, 0.5], [2.0, 0.5]]

In that example, how save_to_convenient_for_parsing_file and read_from_convenient_for_parsing_file should look?

like image 419
Nourless Avatar asked Mar 22 '26 19:03

Nourless


1 Answers

One of the most natural ways to store objects in Python is pickle and it is supported in Julia:

import pickle
with open("a.pkl","wb") as f:
    pickle.dump(a,f)

And now you can do:

julia> using Pickle

julia> Pickle.load("a.pkl")
2-element Vector{Any}:
 Any[Any[0, 1]]
 Any[Any[1, 0.5], Any[2, 0.5]]

Note that an equivalent of Python's list is a Julia's vector of Any values as lists in Python are not typed.

A more universal format would be BSON:

import bson
with open("a.bson","wb") as f:
   f.write(bson.dumps({"a":a}))
julia> using BSON

julia> BSON.load("a.bson")
Dict{Symbol, Any} with 1 entry:
  :a => Any[Any[Any[0, 1]], Any[Any[1, 0.5], Any[2, 0.5]]]
like image 142
Przemyslaw Szufel Avatar answered Mar 24 '26 08:03

Przemyslaw Szufel