KyleJT
1
I have a code as the following:
list = []
for itr in "Watch out! Hello, world"
if isletter(itr)
append!(list,itr)
end
end
println(list)
How can I convert the above code snippet into an array comprehension? Something like:
[isletter(itr) ? itr : $(give it up) for itr in str]
Maybe you can use a generator expression with the if
keyword:
(Multi-dimensional Arrays · The Julia Language)
str = "Watch out! Hello, world"
[ c for c in str if isletter(c) ]
2 Likes
KyleJT
3
Thanks, your solution works. Inspired by your work, I found another tech:
filter(isletter, str)
2 Likes
DNF
4
Be aware that this is a bad idea. It will force your output array to have eltype Any
. In order to initialize an empty vector of characters write:
list = Char[]
Initializing arrays with a plain []
is a serious performance trap.
2 Likes
KyleJT
5
Get it! Thanks for your explanations.