在 python 中制作一个 4x4 数组
Making a 4x4 array in python
我正在尝试创建一个看起来像这样的 4x4 数组:This is a javascript code that I'm trying to create into python
[0, 1, 2, 3]
[4、5、6、7]
[8, 9, 10, 11]
[12, 13, 14, 15]
height = 4
width = 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0, height * width, 4):
row = []
for j in range(i, i + width, 1):
row.append(num[j])
print(row)
如果您正在寻找替代建议,我建议您使用 numpy
:
import numpy as np
height, width = 4, 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
array = np.array(num).reshape((height, width))
print(array)
输出:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
看看这个:
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def check(num,each=4):
for i in range(0,num,each):
print(num[i:i+4])
check(16,4)
有点小错误...!
height = 4
width = 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0, height*width, 4):
row = []
for j in range(i, i+width):
row.append(num[j])
print(row) # this statement should be outside the second for loop
我正在尝试创建一个看起来像这样的 4x4 数组:This is a javascript code that I'm trying to create into python
[0, 1, 2, 3]
[4、5、6、7]
[8, 9, 10, 11]
[12, 13, 14, 15]
height = 4
width = 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0, height * width, 4):
row = []
for j in range(i, i + width, 1):
row.append(num[j])
print(row)
如果您正在寻找替代建议,我建议您使用 numpy
:
import numpy as np
height, width = 4, 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
array = np.array(num).reshape((height, width))
print(array)
输出:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
看看这个:
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def check(num,each=4):
for i in range(0,num,each):
print(num[i:i+4])
check(16,4)
有点小错误...!
height = 4
width = 4
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for i in range(0, height*width, 4):
row = []
for j in range(i, i+width):
row.append(num[j])
print(row) # this statement should be outside the second for loop