我希望从一维列表中以最pythonic的方式填充3x3矩阵。
所以从第一个转换到第二个
[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 :(得分: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]]
答案 1 :(得分: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)]