Python程序将列表转换为矩阵,每行的大小增加一个数字
给定一个列表和一个数字 N,这里的任务是编写一个Python程序将其转换为矩阵,其中每行比列表中的前一行元素多 N 个元素。
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 3
Output : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Explanation : Each row has 3 elements more than previous row.
Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], N = 4
Output : [[4, 6, 8, 1], [4, 6, 8, 1, 2, 9, 0, 10], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
Explanation : Each row has 4 elements more than previous row.
方法 1:使用循环和切片
在这里,我们使用切片执行获取块的任务,并使用循环完成列表到矩阵的转换。
程序:
Python3
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing N
N = 3
res = []
for idx in range(0, len(test_list) // N):
# getting incremented chunks
res.append(test_list[0: (idx + 1) * N])
# printing result
print("Constructed Chunk Matrix : " + str(res))
Python3
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing N
N = 3
# getting incremented chunks
# using list comprehension as shorthand
res = [test_list[0: (idx + 1) * N] for idx in range(0, len(test_list) // N)]
# printing result
print("Constructed Chunk Matrix : " + str(res))
输出:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]
方法 2:使用列表理解和列表切片
在这里,我们使用列表理解作为速记来执行设置值的任务。其余所有操作均与上述方法类似。
程序:
蟒蛇3
# initializing list
test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing N
N = 3
# getting incremented chunks
# using list comprehension as shorthand
res = [test_list[0: (idx + 1) * N] for idx in range(0, len(test_list) // N)]
# printing result
print("Constructed Chunk Matrix : " + str(res))
输出:
The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]
Constructed Chunk Matrix : [[4, 6, 8], [4, 6, 8, 1, 2, 9], [4, 6, 8, 1, 2, 9, 0, 10, 12], [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]]