What's the easiest way in Julia to call a function n times, with the same arguments, and return the result in an array? For example, I'd like to get an array of random strings, each of a certain length. The best I've been able to come up with is
julia> map(_ -> randstring(4), 1:6)
6-element Array{String,1}:
"xBWv"
"CxJm"
"KsHk"
"UUIP"
"64o4"
"QNgm"
Run Code Online (Sandbox Code Playgroud)
Another alternative is to use broadcasting, like in either of the following:
# Broadcast over an array of 4's
randstring.(fill(4, 6))
# Broadcast over an iterator that repeats the number 4 six times
using Base.Iterators
randstring.(repeated(4, 6))
Run Code Online (Sandbox Code Playgroud)
However, my preference is for a syntax like replicate(randstring(4), 6). For comparison, in R I would do the following:
julia> map(_ -> randstring(4), 1:6)
6-element Array{String,1}:
"xBWv"
"CxJm"
"KsHk"
"UUIP"
"64o4"
"QNgm"
Run Code Online (Sandbox Code Playgroud)
Luf*_*ufu 10
我会去
using Random
six_randstrings = [randstring(4) for _ in 1:6]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
133 次 |
| 最近记录: |