31

如何在 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)
4

1 回答 1

54

使用transpose

> zipped = x.zip(y)
=> [[1, 4], [2, 5], [3, 6]]
> x2, y2 = zipped.transpose
> x2
=> [1, 2, 3]
> y2
=> [4, 5, 6]
于 2013-04-02T00:36:52.083 回答