如何在 Ruby 中解压缩数组,就像 Python 中的这个示例:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
使用transpose
:
> zipped = x.zip(y)
=> [[1, 4], [2, 5], [3, 6]]
> x2, y2 = zipped.transpose
> x2
=> [1, 2, 3]
> y2
=> [4, 5, 6]