gpt4 book ai didi

julia - 在可变数量的列表上使用 Iterators.product

转载 作者:行者123 更新时间:2023-12-04 08:49:49 25 4
gpt4 key购买 nike

我正在尝试创建一个在可变数量的数组上使用 Iterators.product() 的函数。
这是我的代码:

function make_feature_space(dictionary, k)
dict_chars = collect(dictionary)
#Change bottom line
dict_product = collect(Iterators.product(dict_chars))
return dict_product
end
我想要的行为类似于调用 make_feature_space(dictionary, 3)将返回 Iterators.product(dict_chars, dict_chars, dict_chars) , 但调用 make_feature_space(dictionary, 2)会得到 Iterators.product(dict_chars, dict_chars) .
谢谢!!

最佳答案

这是一个使用 Iterators.repeated 的解决方案和 splatting :

using Base.Iterators

make_feature_space(x, n) = product(repeated(x, n)...)
这是在行动:
julia> x = 1:2;

julia> make_feature_space(x, 2) |> collect
2×2 Array{Tuple{Int64,Int64},2}:
(1, 1) (1, 2)
(2, 1) (2, 2)

julia> make_feature_space(x, 3) |> collect
2×2×2 Array{Tuple{Int64,Int64,Int64},3}:
[:, :, 1] =
(1, 1, 1) (1, 2, 1)
(2, 1, 1) (2, 2, 1)

[:, :, 2] =
(1, 1, 2) (1, 2, 2)
(2, 1, 2) (2, 2, 2)
请注意,此实现可以在 make_feature_space 的第一个参数中使用任何迭代器。 .进一步注意,字典是对的迭代器,所以你可以这样做:
julia> d = Dict(:a => 1, :b => 2)
Dict{Symbol,Int64} with 2 entries:
:a => 1
:b => 2

julia> make_feature_space(d, 2) |> collect
2×2 Array{Tuple{Pair{Symbol,Int64},Pair{Symbol,Int64}},2}:
(:a=>1, :a=>1) (:a=>1, :b=>2)
(:b=>2, :a=>1) (:b=>2, :b=>2)
尽管从您的问题中不清楚您是否正在通过字典的键、值或对寻找产品。

关于julia - 在可变数量的列表上使用 Iterators.product,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64147685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com