The following does what I want, generate a vector of tuples thanks to the two vectors that I provide.
xycoordinates = Tuple{Int,Int}[(x,y) for x in collect(1:10), y in rand(1:10, 10)]
I wanted to know if there exists a better way for doing this or is it already optimal, in terms of code readability and conciseness.
tuple.(x, y)
? Though I think you are creating tuple.(x, y')
in your example actually
2 Likes
Thanks! Plus there was a mistake in my code, I generated a matrix instead of a vector.
1 Like
A side remark: There are some unnecessary allocations in your code. You can just use 1:10
instead of collect(1:10)
. And rand(1:10, 10)
also creates a vector that it not really needed.
Iām not sure if you want a vector with 10 or with 100 elements as the result. In the first case you can say
[(x, rand(1:10)) for x in 1:10]
and in the second
[(x, rand(1:10)) for x in 1:10 for _ in 1:10]
2 Likes
DNF
July 31, 2024, 5:58pm
5
Indeed, and also, the type annotation is redundant here (as also demonstrated by your example)
K5Julien:
Tuple{Int,Int}[(x,y) for x in collect(1:10), y in rand(1:10, 10)]
One can simply allow the comprehension to determine the type automatically.
1 Like