2017-02-13 51 views
0

我正在尋找從1D列表中以最pythonic方式填充3x3矩陣。用M矩陣填充M與1D列表python

所以從第一轉變爲第二

[1,2,3,4,5,6,7,8,9] 

[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] 

到目前爲止,我可以填寫第一次作爲這樣的:

l = [1,2,3,4,5,6,7,8,9] 
m = [[l[y] for y in range(3)] for x in range(3)] 

但是這給

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] 
+0

看到numpy.reshape https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html –

回答

0

你可以做些什麼像這樣使用list comprehension

a = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
b = [a[k:k+3] for k in range(0,len(a),3)] 

輸出:

print(b) 
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

您也可以創建這種情況下的方法來處理你的數組的大小調整:

def reshape(a = list, r = 1): 
    return [a[k:k+r] for k in range(0,len(a),r)] 

a = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

輸出:

print(reshape(a, 3)) 
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
print(reshape(a,2)) 
>>> [[1, 2], [3, 4], [5, 6], [7, 8], [9]] 
0

考慮:

l = [1,2,3,4,5,6,7,8,9] 

您可以創建N iterators,然後zip將它們放在一起。該技術在grouper文檔的itertools Recipes部分進行了描述。

def grouper(iterable, n, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return zip_longest(*args, fillvalue=fillvalue) 

print(list(grouper(l, 3))) 

輸出:

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]