簡體   English   中英

Numpy:重塑元組列表

[英]Numpy: reshape list of tuples

我有以下元組列表:

>>> import itertools
>>> import numpy as np
>>> grid = list(itertools.product((1,2,3),repeat=2))
>>> grid
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

我想以一種合理的方式重塑此列表(例如,如果可能,使用 numpy)為 3x3,如下所示:

[[(1, 1), (1, 2), (1, 3)],
 [(2, 1), (2, 2), (2, 3)],
 [(3, 1), (3, 2), (3, 3)]]

當我執行np.reshape(grid, (3, 3))時出現以下錯誤: ValueError: cannot reshape array of size 18 into shape (3,3) (size 18??)

我試過np.reshape(grid, (3, 3, 2))的變體,但這些變體不會返回上面給出的 3x3 網格。

這將完成工作:

new_grid = np.empty(len(grid), dtype='object')
new_grid[:] = grid
new_grid = new_grid.reshape(3, 3)

這輸出:

array([[(1, 1), (1, 2), (1, 3)],
       [(2, 1), (2, 2), (2, 3)],
       [(3, 1), (3, 2), (3, 3)]], dtype=object)

object 類型將保留為元組:

type(new_grid[0, 0])
tuple

18是因為您有一個包含9元組的列表,每個元組包含2項目; 因此, 9 * 2 = 18 numpy 自動將元組轉換為數組的一部分。

您可以使用LeonardoVaz 的答案,也可以使用嵌套列表理解快速完成:

reshaped_grid = [[grid[i+j] for j in range(3)] for i in range(0, len(grid), 3)]

Output:

>>> reshaped_grid
[
    [(1, 1), (1, 2), (1, 3)],
    [(2, 1), (2, 2), (2, 3)],
    [(3, 1), (3, 2), (3, 3)]
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM