📜  从列表构造 n*m 矩阵的Python程序

📅  最后修改于: 2022-05-13 01:55:16.775000             🧑  作者: Mango

从列表构造 n*m 矩阵的Python程序

给定一个列表,任务是编写一个可以构造 n*m 矩阵的Python程序。

方法:使用嵌套循环

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))


输出:

示例 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))

输出: