Python - 将后续行分配给矩阵第一行元素
给定一个 (N + 1) * N 矩阵,分配矩阵的第一行的每一列,矩阵的后续行。
Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]}
Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th
Input : test_list = [[5, 8], [2, 0], [5, 4]]
Output : {5: [2, 0], 8: [5, 4]}
Explanation : 5 paired with 2nd row, 8 with 3rd.
方法#1:使用字典理解
这是可以执行此任务的方式之一。在此,我们使用循环迭代行和对应的列,并使用字典理解以单行方式相应地分配值列表。
Python3
# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
# Using dictionary comprehension
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
# printing original list
print("The original list : " + str(test_list))
# pairing each 1st col with next rows in Matrix
res = {test_list[0][ele] : test_list[ele + 1] for ele in range(len(test_list) - 1)}
# printing result
print("The Assigned Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
# Using zip() + list slicing + dict()
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
# printing original list
print("The original list : " + str(test_list))
# dict() to convert back to dict type
# slicing and pairing using zip() and list slicing
res = dict(zip(test_list[0], test_list[1:]))
# printing result
print("The Assigned Matrix : " + str(res))
输出
The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}
方法 #2:使用 zip() + 列表切片 + dict()
这是可以执行此任务的另一种方式。在此,我们使用列表切片将元素切片为第一行和后续行,并且 zip() 执行所需分组的任务。回来
Python3
# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
# Using zip() + list slicing + dict()
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
# printing original list
print("The original list : " + str(test_list))
# dict() to convert back to dict type
# slicing and pairing using zip() and list slicing
res = dict(zip(test_list[0], test_list[1:]))
# printing result
print("The Assigned Matrix : " + str(res))
输出
The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}