有一个类似input = [[“a”,“b”,“c”],[1,2,3],[“e”,“f”,“g”],…], 里面的长度不限;需要对里面每一个元素形成一个元组为元素的数组格式数据。里面的格式,对原来的元素的格式不进行破坏。
当输入:
input = [["a","b","c"],[1,2,3],["e","f","g"]],
输出:
27-element Vector{Tuple{Char, Int64, String}}:
('a', 1, "e")
('a', 1, "f")
('a', 1, "g")
('a', 2, "e")
('a', 2, "f")
('a', 2, "g")
⋮
('c', 2, "f")
('c', 2, "g")
('c', 3, "e")
('c', 3, "f")
('c', 3, "g")
代码如下:
function f(input)
output =[]
len = length(input)
if len == 1
return input
elseif len ==0
error("input is empty!")
end
for i = 1:len-1
if i == 1
output = g(input[1],input[i+1])
else
output = g(output,input[i+1])
end
end
return output
end
function g(a,b)
return [(i...,j) for i in a for j in b]
end
上面的代码很一般,但是我认为“…”的用法很好,如果没有…,就会形成:
julia> f()
27-element Vector{Tuple{Tuple{String, Int64}, String}}:
(("a", 1), "e")
(("a", 1), "f")
(("a", 1), "g")
(("a", 2), "e")
(("a", 2), "f")
(("a", 2), "g")
⋮
(("c", 2), "f")
(("c", 2), "g")
(("c", 3), "e")
(("c", 3), "f")
(("c", 3), "g")
显然,这个并不是我们要的。所以,因为加了…这么一点点,结果就是很神奇!
进一步,我们把input变得更复杂,测试一下结果:
julia> arr_data = [["a","b","c"],[1,2,3],["e","f","g"],[1.0,2.0,5.0,6.0,7.0,8.0,9.0],["hello","world"],[["we"],["are"],["together!"]]]
6-element Vector{Vector{T} where T}:
["a", "b", "c"]
[1, 2, 3]
["e", "f", "g"]
[1.0, 2.0, 5.0, 6.0, 7.0, 8.0, 9.0]
["hello", "world"]
[["we"], ["are"], ["together!"]]
julia> f(arr_data)
1134-element Vector{Tuple{Char, Int64, String, Float64, String, Vector{String}}}:
('a', 1, "e", 1.0, "hello", ["we"])
('a', 1, "e", 1.0, "hello", ["are"])
('a', 1, "e", 1.0, "hello", ["together!"])
('a', 1, "e", 1.0, "world", ["we"])
('a', 1, "e", 1.0, "world", ["are"])
('a', 1, "e", 1.0, "world", ["together!"])
('a', 1, "e", 2.0, "hello", ["we"])
('a', 1, "e", 2.0, "hello", ["are"])
('a', 1, "e", 2.0, "hello", ["together!"])
('a', 1, "e", 2.0, "world", ["we"])
('a', 1, "e", 2.0, "world", ["are"])
('a', 1, "e", 2.0, "world", ["together!"])
('a', 1, "e", 5.0, "hello", ["we"])
⋮
('c', 3, "g", 7.0, "world", ["together!"])
('c', 3, "g", 8.0, "hello", ["we"])
('c', 3, "g", 8.0, "hello", ["are"])
('c', 3, "g", 8.0, "hello", ["together!"])
('c', 3, "g", 8.0, "world", ["we"])
('c', 3, "g", 8.0, "world", ["are"])
('c', 3, "g", 8.0, "world", ["together!"])
('c', 3, "g", 9.0, "hello", ["we"])
('c', 3, "g", 9.0, "hello", ["are"])
('c', 3, "g", 9.0, "hello", ["together!"])
('c', 3, "g", 9.0, "world", ["we"])
('c', 3, "g", 9.0, "world", ["are"])
('c', 3, "g", 9.0, "world", ["together!"])