Python – 自定义列矩阵
有时,在使用Python列表时,我们可能会遇到需要从 Matrix 中提取某些列并重新创建它的问题。这类问题可以在数据域中应用,因为它们使用 Matrix 作为突出的输入参数。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[5, 4, 3, 4], [7, 6, 3, 2], [8, 3, 9, 10]], col_list = [2]
Output : [[3], [3], [9]]
Input : test_list = [[5, 4], [6, 2], [8, 3]], col_list = [1]
Output : [[4], [2], [3]]
方法#1:使用列表推导
这提供了解决此问题的方法之一。在此,我们使用嵌套列表推导执行选择性列的提取。
# Python3 code to demonstrate working of
# Custom Columns Matrix
# Using list comprehension
# initializing list
test_list = [[5, 4, 3, 4],
[7, 6, 3, 2],
[8, 3, 9, 10]]
# printing original list
print("The original list : " + str(test_list))
# initializing Columns list
col_list = [1, 3]
# Custom Columns Matrix
# Using list comprehension
res = [[sub[idx] for idx in col_list] for sub in test_list]
# printing result
print("Matrix after filtering : " + str(res))
输出 :
The original list : [[5, 4, 3, 4], [7, 6, 3, 2], [8, 3, 9, 10]]
Matrix after filtering : [[4, 4], [6, 2], [3, 10]]
方法 #2:使用itemgetter()
+ 列表推导
上述功能的组合可以用来解决这个问题。在此,我们使用 itemgetter() 执行获取索引的任务。
# Python3 code to demonstrate working of
# Custom Columns Matrix
# Using itemgetter() + list comprehension
from operator import itemgetter
# initializing list
test_list = [[5, 4, 3, 4],
[7, 6, 3, 2],
[8, 3, 9, 10]]
# printing original list
print("The original list : " + str(test_list))
# initializing Columns list
col_list = [1, 3]
# Custom Columns Matrix
# Using itemgetter() + list comprehension
res = [list(itemgetter(*col_list)(ele)) for ele in test_list]
# printing result
print("Matrix after filtering : " + str(res))
输出 :
The original list : [[5, 4, 3, 4], [7, 6, 3, 2], [8, 3, 9, 10]]
Matrix after filtering : [[4, 4], [6, 2], [3, 10]]