Stream: helpdesk (published)

Topic: Repeating a variable number of times


view this post on Zulip Timothy (Jun 24 2021 at 06:12):

I feel like there has to be something nicer than this

[repeat([a], b) for (a, b) in zip(["a", "b"], [2, 3])] |> Iterators.flatten |> collect

If someone could help me work out what, that would be grand.

view this post on Zulip Timothy (Jun 24 2021 at 06:16):

Update: thanks to further googling I have found reduce(vcat, fill.(["a", "b"], [2, 3])). I'm guessing there's no nice way to do this? repeat(["a", "b"], [2, 3]) would be ideal...

view this post on Zulip Andrey Oskin (Jun 24 2021 at 08:48):

You can do mapreduce(x -> fill(x[1], x[2]), vcat, zip(["a", "b"], [2, 3])), but not sure whether it is better than other versions.

view this post on Zulip Mosè Giordano (Jun 24 2021 at 09:53):

string.(collect(join(repeat.(["a", "b"], (2, 3))))) but I doubt this is also any better than other solutions :laughing:

view this post on Zulip Patrick Toche (Jun 24 2021 at 10:35):

Here's another way to repeat, quite elegant:

["a", "b"].^[2, 3]
## String["aa", "bbb"]

But then you still need to split your "aa" into "a","a", etc..

view this post on Zulip Timothy (Jun 24 2021 at 11:50):

The .^ trick is pretty nice for strings. I think I might just have to accept that my generic ideal "easy" form isn't built into Julia somewhere.

view this post on Zulip Nils (Jun 24 2021 at 13:14):

For this specific case you can also do [i < 3 ? "a" : "b" for i ∈ 1:5]


Last updated: Oct 02 2023 at 04:34 UTC