2

zip次のように、2 つの配列が 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
4

3 に答える 3

6

私は書くだろう:

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]
于 2012-12-29T20:59:27.053 に答える
0

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) 
于 2012-12-29T23:57:52.923 に答える
0

どうですか:

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]
于 2012-12-29T23:20:11.250 に答える