过滤掉矩阵非空行的Python程序
给定矩阵,下面的文章展示了如何过滤矩阵的所有非空行。简单来说,下面提供的代码在从中删除空行后返回一个矩阵。
Input : test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []]
Output : [[4, 5, 6, 7], [9, 8, 1]]
Explanation : All empty rows are removed.
Input : test_list = [[4, 5, 6, 7], [], [9, 8, 1], []]
Output : [[4, 5, 6, 7], [9, 8, 1]]
Explanation : All empty rows are removed.
方法 1:使用列表推导和len()
在这里,我们检查每一行的长度,如果其长度大于 0,则将该行添加到结果中。
Python3
# initializing list
test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []]
# printing original lists
print("The original list is : " + str(test_list))
# checking for row lengths using len()
res = [row for row in test_list if len(row) > 0]
# printing result
print("Filtered Matrix " + str(res))
Python3
# initializing list
test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []]
# printing original lists
print("The original list is : " + str(test_list))
# checking for row lengths using len()
# filtering using filter() + lambda
res = list(filter(lambda row: len(row) > 0, test_list))
# printing result
print("Filtered Matrix " + str(res))
输出:
The original list is : [[4, 5, 6, 7], [], [], [9, 8, 1], []]
Filtered Matrix [[4, 5, 6, 7], [9, 8, 1]]
方法二:使用filter(), lambda和len()
在这里,我们使用 filter() 和 lambda函数过滤行和长度。 len() 用于获取长度。
蟒蛇3
# initializing list
test_list = [[4, 5, 6, 7], [], [], [9, 8, 1], []]
# printing original lists
print("The original list is : " + str(test_list))
# checking for row lengths using len()
# filtering using filter() + lambda
res = list(filter(lambda row: len(row) > 0, test_list))
# printing result
print("Filtered Matrix " + str(res))
输出:
The original list is : [[4, 5, 6, 7], [], [], [9, 8, 1], []]
Filtered Matrix [[4, 5, 6, 7], [9, 8, 1]]