【发布时间】:2013-04-02 00:30:03
【问题描述】:
如何在 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)
【问题讨论】:
如何在 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]
【讨论】:
x.size > y.size,transpose 不是zip 的倒数,因为它会将nils 添加到y2 的末尾。如果两个原件都不包含 nil,则使用 zipped.transpose.map(&:compact) 恢复原件。