I am new with Julia. I was wandering if it is possible to write in a single line an if statement in an array or a set in Julia.
For example in python I can write a list such as
s = [1 if np.random.uniform() < 0.5 else 0 for i in range(10)]
which in Julia, if I'm right, should be an array like this
s = []
for i in 0:10
if rand()<0.5
push!(s, 1)
else
push!(s, 0)
end
end
I know I can write the for cycle in a single line i.e.
s =[1 for i in 1:10]
But what about the if..else statement?
as @Guido suggested, you can use list comprehension just like python, more specifically:
s = [if rand() < 0.5 1 else 0 end for i in 1:10]
note that julia's if-else statement needs an end. i think this is the same as using map:
map(x -> rand() < 0.5 ? 1 : 0, 1:10)
To specifically do,
s = [1 if np.random.uniform() < 0.5 else 0 for i in range(10)]
In Julia you can write,
s = [rand()<0.5?1:0 for i=1:10]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With