从矩阵打印给定长度的行的Python程序
给定一个矩阵,以下文章展示了如何提取指定长度的所有行。
Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]], K = 3
Output : [[1, 4, 6], [7, 3, 1]]
Explanation : Extracted lists have length of 3.
Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]], K = 4
Output : [[3, 4, 5, 6]]
Explanation : Extracted lists have length of 4.
方法 1:使用列表推导和len()
在这里,我们使用 len() 执行获取长度的任务,列表推导式执行过滤所有具有指定长度的行的任务。
Python3
# initializing list
test_list = [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# list comprehension is used for extracting K len rows
res = [sub for sub in test_list if len(sub) == K]
# printing result
print("The filtered rows : " + str(res))
Python3
# initializing list
test_list = [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# filter() + lambda to filter out rows of len K
res = list(filter(lambda sub: len(sub) == K, test_list))
# printing result
print("The filtered rows : " + str(res))
输出:
The original list is : [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]]
The filtered rows : [[1, 4, 6], [7, 3, 1]]
方法 2:使用filter() 、 lambda和len()
在此,我们使用 filter() 和 lambda 执行过滤任务。 len() 用于查找行的长度。
蟒蛇3
# initializing list
test_list = [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# filter() + lambda to filter out rows of len K
res = list(filter(lambda sub: len(sub) == K, test_list))
# printing result
print("The filtered rows : " + str(res))
输出:
The original list is : [[3, 4, 5, 6], [1, 4, 6], [2], [2, 3, 4, 5, 6], [7, 3, 1]]
The filtered rows : [[1, 4, 6], [7, 3, 1]]