是否有这样一种方式,2个阵列将用正元件之间的空间,例如将拉链使用zip
一种方式:与每第n个元件正在压缩阵列
a = [1,2,3,4,5,6,7,8,9,10]
b = ["x","y","z"]
n = 3
结果将是
res = [[1,"x"],2,3,[4,"y"],5,6,[7,"z"],8,9,10] # note that 10 is alone and b is not cycled
是否有这样一种方式,2个阵列将用正元件之间的空间,例如将拉链使用zip
一种方式:与每第n个元件正在压缩阵列
a = [1,2,3,4,5,6,7,8,9,10]
b = ["x","y","z"]
n = 3
结果将是
res = [[1,"x"],2,3,[4,"y"],5,6,[7,"z"],8,9,10] # note that 10 is alone and b is not cycled
我会写:
res = a.each_slice(n).zip(b).flat_map do |xs, y|
y ? [[xs.first, y], *xs.drop(1)] : xs
end
#=> [[1, "x"], 2, 3, [4, "y"], 5, 6, [7, "z"], 8, 9, 10]
如何:
a.map.with_index{|x, i| i%n < 1 && b.size > i/n ? [x, b[i/n]] : x}
#=> [[1, "x"], 2, 3, [4, "y"], 5, 6, [7, "z"], 8, 9, 10]
你确定吗?这导致'[[10,“x”]]'在这里。 – steenslag
也许你有一个额外的x在你的b? – pguardiario
我很抱歉你的时间 - 无法重现输出。 – steenslag
遍历b为一种可能性:
# Note this destroys array a;use a dup it if it is needed elsewhere
res = b.flat_map{|el| [[el].unshift(a.shift), *a.shift(n-1)] }.concat(a)
你可以学到很多从Haskell的东西,其中之一就是用复数名的集合('as','bs'),并保持单数('a','b')的元素。 – tokland