julia與python類似之處

lt發表於2017-05-04

1.使用列表推導計算笛卡兒積

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> tshirts = [(color, size) for color in colors for size in sizes] ➊
>>> tshirts
[('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'),
 ('white', 'M'), ('white', 'L')]

#julia除了表示字串要用雙引號,其餘照抄 
julia>  colors = ['black', 'white']
ERROR: syntax: invalid character literal

julia>  colors = ["black", "white"]
2-element Array{String,1}:
 "black"
 "white"

julia> sizes = ["S", "M", "L"]
3-element Array{String,1}:
 "S"
 "M"
 "L"

julia> tshirts = [(color, size) for color in colors for size in sizes]
6-element Array{Tuple{String,String},1}:
 ("black", "S")
 ("black", "M")
 ("black", "L")
 ("white", "S")
 ("white", "M")
 ("white", "L")

2.生成器表示式

>>> colors = ['black', 'white'] 
>>> sizes = ['S', 'M', 'L'] 
>>> for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):  ➊ 
...     print(tshirt) 
... 
black S 
black M 
black L 
white S 
white M 
white L
#julia除了輸出格式字串不同,其餘照抄
julia> colors = ["black", "white"]
2-element Array{String,1}:
 "black"
 "white"

julia> sizes = ["S", "M", "L"]
3-element Array{String,1}:
 "S"
 "M"
 "L"

julia> for tshirt in ("$c, $s" for c in colors for s in sizes)
       println(tshirt)
       end
black, S
black, M
black, L
white, S
white, M
white, L
#生成器表示式可以賦值給一個變數
julia> ge=("$c, $s" for c in colors for s in sizes)
Base.Iterators.Flatten{Base.Generator{Array{String,1},##17#19}}(Base.Generator{A
rray{String,1},##17#19}(#17, String["black", "white"]))

julia> for tshirt in ge
       println(tshirt)
       end
black, S
black, M
black, L
white, S
white, M
white, L

相關文章