从矩阵中打印出在给定索引处具有相同元素的行的Python程序
给定一个矩阵,下面的文章展示了如何提取在指定索引处具有相似数字的行并将其作为输出返回。
Input : test_list = [[3345, 6355, 83, 938], [323, 923, 845], [192, 993, 49], [98, 34, 23]], K = 1
Output : [[3345, 6355, 83, 938], [192, 993, 49]]
Explanation : 3 and 9 [ same ] in 1st column.
Input : test_list = [[3445, 6355, 83, 938], [323, 923, 845], [192, 993, 49], [98, 34, 23]], K = 1
Output : [[192, 993, 49]]
Explanation : 9 in 1st column.
方法 1:使用 all() 和列表推导式
在这里,我们使用 all() 检查指定索引处的所有数字,并使用列表理解来迭代每一行。
Python3
# initializing list
test_list = [[3345, 6355, 83, 938], [
323, 923, 845], [192, 993, 49], [98, 34, 23]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# checking for all elements match using all()
res = [row for row in test_list if all(
str(i)[K] == str(row[0])[K] for i in row)]
# printing result
print("Filtered Rows : " + str(res))
Python3
# initializing list
test_list = [[3345, 6355, 83, 938], [
323, 923, 845], [192, 993, 49], [98, 34, 23]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# checking for all elements match using all()
# filter() and lambda function performing filtering
res = list(filter(lambda row: all(
str(i)[K] == str(row[0])[K] for i in row), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[3345, 6355, 83, 938], [323, 923, 845], [192, 993, 49], [98, 34, 23]]
Filtered Rows : [[3345, 6355, 83, 938], [192, 993, 49]]
方法 2:使用filter() 、 lambda和 all()
在这里,我们检查所有行是否有相似的 K 列数字,使用 filter() 和 lambda函数进行过滤。与上述方法类似, all() 执行检查每个元素的任务。
蟒蛇3
# initializing list
test_list = [[3345, 6355, 83, 938], [
323, 923, 845], [192, 993, 49], [98, 34, 23]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# checking for all elements match using all()
# filter() and lambda function performing filtering
res = list(filter(lambda row: all(
str(i)[K] == str(row[0])[K] for i in row), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[3345, 6355, 83, 938], [323, 923, 845], [192, 993, 49], [98, 34, 23]]
Filtered Rows : [[3345, 6355, 83, 938], [192, 993, 49]]