省略K长度行的Python程序
给定一个矩阵,删除长度为 K 的行。
Input : test_list = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]], K = 2
Output : [[8, 10, 12, 8], [6, 8, 10]]
Explanation : [4, 7] and [10, 11] omitted as length 2 rows.
Input : test_list = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]], K = 3
Output : [[4, 7], [8, 10, 12, 8], [10, 11]]
Explanation : [6, 8, 10] omitted as length 3 rows.
方法 #1:使用循环 + len()
在此,我们使用 len() 检查每一行的长度,如果发现等于 K,则从 Matrix 中省略该行。
Python3
# Python3 code to demonstrate working of
# Omit K length Rows
# Using loop + len()
# initializing list
test_list = [[4, 7],
[8, 10, 12, 8],
[10, 11],
[6, 8, 10]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = []
for row in test_list:
# checking rows not K length
if len(row) != K :
res.append(row)
# printing result
print("Filtered Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Omit K length Rows
# Using filter() + lambda + len()
# initializing list
test_list = [[4, 7],
[8, 10, 12, 8],
[10, 11],
[6, 8, 10]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# getting elements with length other than K
res = list(filter(lambda row : len(row) != K, test_list))
# printing result
print("Filtered Matrix : " + str(res))
输出:
The original list is : [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]]
Filtered Matrix : [[8, 10, 12, 8], [6, 8, 10]]
方法 #2:使用 filter() + lambda + len()
在这里,我们使用 filter() 来提取长度不是 K 的行。 lambda函数用于呈现长度计算逻辑。
蟒蛇3
# Python3 code to demonstrate working of
# Omit K length Rows
# Using filter() + lambda + len()
# initializing list
test_list = [[4, 7],
[8, 10, 12, 8],
[10, 11],
[6, 8, 10]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# getting elements with length other than K
res = list(filter(lambda row : len(row) != K, test_list))
# printing result
print("Filtered Matrix : " + str(res))
输出:
The original list is : [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]]
Filtered Matrix : [[4, 7], [10, 11], [6, 8, 10]]