22
如何解壓一個數組中的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'是不太逆因爲它會在'y2'的末尾添加'nil'。如果兩個原始文件都不包含使用'zipped.transpose.map(&:compact)'的零'恢復原件。 – dbenhur
@dbenhur這是真的。 –