从列表构造 n*m 矩阵的Python程序
给定一个列表,任务是编写一个可以构造 n*m 矩阵的Python程序。
Input : test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3], n, m = 3, 5
Output : “Matrix Not Possible”
Explanation : List has 12 elements and 3*5 is 15, hence Matrix not possible.
Input : test_list = [6, 3, 7, 2, 6, 8], n, m = 2, 3
Output : [[6, 3, 7], [2, 6, 8]]
Explanation : List converted to 2*3 matrix.
方法:使用嵌套循环
n*m 的约束将列表的大小限制为严格的 n*m。实现后,我们可以使用嵌套循环分配适当的行和列。
示例 1:
Python3
# Python3 code to demonstrate working of
# Construct n*m Matrix from List
# Using loop
# initializing list
test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing n, m
n, m = 3, 4
k = 0
res = []
if n*m != len(test_list):
# checking if Matrix Possible
res = "Matrix Not Possible"
else:
# Constructing Matrix
for idx in range(0, n):
sub = []
for jdx in range(0, m):
sub.append(test_list[k])
k += 1
res.append(sub)
# printing result
print("Constructed Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Construct n*m Matrix from List
# Using loop
# initializing list
test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing n, m
n, m = 5, 4
k = 0
res = []
# n*m == 20 > length, hence result not possible.
if n*m != len(test_list):
# checking if Matrix Possible
res = "Matrix Not Possible"
else:
# Constructing Matrix
for idx in range(0, n):
sub = []
for jdx in range(0, m):
sub.append(test_list[k])
k += 1
res.append(sub)
# printing result
print("Constructed Matrix : " + str(res))
输出:
The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
Constructed Matrix : [[6, 3, 7, 2], [6, 8, 4, 3], [9, 2, 1, 3]]
示例 2:
蟒蛇3
# Python3 code to demonstrate working of
# Construct n*m Matrix from List
# Using loop
# initializing list
test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing n, m
n, m = 5, 4
k = 0
res = []
# n*m == 20 > length, hence result not possible.
if n*m != len(test_list):
# checking if Matrix Possible
res = "Matrix Not Possible"
else:
# Constructing Matrix
for idx in range(0, n):
sub = []
for jdx in range(0, m):
sub.append(test_list[k])
k += 1
res.append(sub)
# printing result
print("Constructed Matrix : " + str(res))
输出:
The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
Constructed Matrix : Matrix Not Possible