Nested list comprehensions in Julia

前端 未结 5 1036
无人共我
无人共我 2021-02-13 16:14

In python I can do nested list comprehensions, for instance I can flatten the following array thus:

a = [[1,2,3],[4,5,6]]
[i for arr in a for i in arr]
         


        
5条回答
  •  故里飘歌
    2021-02-13 16:26

    Don't have enough reputation for comment so posting a modification @ben-hammer. Thanks for the example of flatten(), it was helpful to me.

    But it did break if the tuples/arrays contained strings. Since strings are iterables the function would further break them down to characters. I had to insert condition to check for ASCIIString to fix that. The code is below

        function flatten(x, y)
            state = start(x)
            if state==false
                push!(y, x)
            else
                if typeof(x) <: String
                    push!(y, x)
                else 
                    while (!done(x, state)) 
                        (item, state) = next(x, state) 
                        flatten(item, y)
                    end
                end
            end
            y
        end
        flatten(x)=flatten(x,Array(Any, 0))
    

提交回复
热议问题