鉴于以下数据类型,以下理解产生两个Array{Any,1}
Player
s:
[[team.players for team in [big_team_1, big_team_2]]]
然而,下一个理解产生了12个元素的Array{Player,1}
的期望结果:
[[team.players for team in [big_team_1, big_team_2]]...]
...
到底在做什么?这记录在哪里?
数据:
type Player
ranking::Int
end
type Team
players::Array{Player}
end
team_1 = Team([Player(10_000), Player(11_000), Player(9_000), Player(8_500),
Player(20_000), Player(10_500)])
team_2 = Team([Player(i.ranking + 3000) for i in team_1.players])
答案 0 :(得分:12)
args...
和; kwargs...
是 splat 运算符,如果您了解Python,则它与*args
和**kwargs
相同:
您可以在此处找到文档:What does the splat ...
operator do?
julia> function foo(pos_1, pos_2, opt_1 = :opt_1, args...;
opt_kw1 = :opt_kw1, opt_kw2 = :opt_kw2, kwargs...)
[pos_1, pos_2, opt_1, args, opt_kw1, opt_kw2, (kwargs,);]
end
foo (generic function with 2 methods)
此签名表示:
pos_1
是第一个必需的位置参数。pos_2
是第二个必要的位置参数。opt_1
是可选的位置参数。args...
是以下所有位置参数,都是在元组中收集的。注意半冒号;
如何将位置参数与关键字参数分开(顺序在关键字参数中不重要):
opt_kw1
是一个可选的关键字参数。opt_kw2
是一个可选的关键字参数。kwargs...
是在元组(键,值)对数组中收集的以下所有关键字参数。julia> methods(foo)
# 2 methods for generic function "foo":
foo(pos_1, pos_2) at none:3
foo(pos_1, pos_2, opt_1, args...) at none:3
foo
可以像这样调用:
julia> foo(:pos_1, :pos_2)
7-element Array{Any,1}:
:pos_1 # provided value
:pos_2 # provided value
:opt_1 # default value
() # empty tuple
:opt_kw1 # default value
:opt_kw2 # default value
(Any[],) # there are no kwargs
可选的位置和关键字参数:
julia> foo(:pos_1, :pos_2, :OPT_1, :a, :b, :c,
opt_kw2 = :OPT_KW2, kwarg1 = true, opt_kw1 = :OPT_KW1, kwarg2 = false)
7-element Array{Any,1}:
:pos_1
:pos_2
:OPT_1
(:a,:b,:c)
:OPT_KW1
:OPT_KW2
(Any[(:kwarg1,true),(:kwarg2,false)],)
注意关键字参数中的顺序是如何不相关的,调用函数时也不需要分号;
。
使用集合为位置参数和assosiative集合以及关键字参数的符号键:
julia> x, y, z = 1, 2, 3;
julia> sum(x, y, z)
ERROR: MethodError: `sum` has no method matching sum(::Int64, ::Int64, ::Int64)
Closest candidates are:
sum(::Union{Base.Func{1},Function}, ::AbstractArray{T,N}, ::Any)
sum(::Union{Base.Func{1},DataType,Function}, ::Any)
sum(::BitArray{N}, ::Any)
...
julia> sum
sum (generic function with 12 methods)
julia> Base.sum(args...) = sum(args)
sum (generic function with 13 methods)
julia> sum(x, y, z)
6
julia> foo(x, y, z) = sum(x, y, z)
foo (generic function with 1 method)
julia> foo(x, y, z)
6
julia> foo([x, y, z])
ERROR: MethodError: `foo` has no method matching foo(::Array{Int64,1})
Closest candidates are:
foo(::Any, ::Any, ::Any)
julia> foo([x, y, z]...)
6
julia> foo(; x = 0, y = 0, z = 0) = sum(x, y, z)
foo (generic function with 2 methods)
julia> foo()
0
julia> foo(z = 3, x = 1, y = 2)
6
julia> foo(; Dict(:z => 3, :y => 2, :x => 1))
ERROR: TypeError: anonymous: in typeassert, expected Symbol, got Pair{Symbol,Int64}
in anonymous at no file
julia> foo(; Dict(:z => 3, :y => 2, :x => 1)...)
6