Reputation: 6355
You can call variables through a loop in Python like this:
var1 = 1
var2 = 2
var3 = 3
for i in range(1,4):
print(globals()[f"var{i}"])
This results in:
1
2
3
Now I'm looking for the equivalent way to call variables using interpolated strings in Julia! Is there any way?
PS: I didn't ask "How to get a list of all the global variables in Julia's active session". I asked for a way to call a local variable using an interpolation in a string.
Upvotes: 1
Views: 111
Reputation: 1743
You don't. Use a collection like an array instead:
julia> values = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> for v in values
println(v)
end
1
2
3
As suggested in earlier comments, dynamically finding the variable names really isn't the approach you want to go for.
Upvotes: 1
Reputation: 42234
List of globals:
vars = filter!(x -> !( x in [:Base, :Core, :InteractiveUtils, :Main, :ans, :err]), names(Main))
Values of globals:
getfield.(Ref(Main), vars)
To display names and values you can either just use varinfo()
or eg. do DataFrames(name=vars,value=getfield.(Ref(Main), vars))
.
Upvotes: 1
Reputation: 296
PS: this is dangerous.
Code:
var1 = 1
var2 = 2
var3 = 3
for i in 1:3
varname = Symbol("var$i")
println(getfield(Main, varname))
end
Upvotes: 3