是否有這樣一種方式,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