Python – 过滤元素为 K 的倍数的行
给定一个矩阵,提取元素为 K 倍数的行。
Input : test_list = [[5, 10, 15], [4, 8, 12], [100, 15], [5, 10, 23]], K = 4
Output : [[4, 8, 12]]
Explanation : All are multiples of 4.
Input : test_list = [[5, 10, 15], [4, 8, 11], [100, 15], [5, 10, 23]], K = 4
Output : []
Explanation : No rows with all multiples of 4.
方法 #1:使用列表理解 + all()
在这种情况下,我们使用 all() 检查所有元素是否为多个元素,并使用列表理解进行行的迭代。
Python3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using list comprehension + all()
# initializing string list
test_list = [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
# printing result
print("Rows with K multiples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using filter() + lambda + all()
# initializing string list
test_list = [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# using all() to check for all elements being multiples of K
res = list(filter(lambda sub : all(ele % K == 0 for ele in sub), test_list))
# printing result
print("Rows with K multiples : " + str(res))
The original list is : [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]]
Rows with K multiples : [[5, 10, 15], [100, 15]]
方法 #2:使用 filter() + lambda + all()
在此,我们使用 filter() 和 lambda函数执行过滤任务以及使用 all() 检查行中所有元素的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using filter() + lambda + all()
# initializing string list
test_list = [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# using all() to check for all elements being multiples of K
res = list(filter(lambda sub : all(ele % K == 0 for ele in sub), test_list))
# printing result
print("Rows with K multiples : " + str(res))
The original list is : [[5, 10, 15], [4, 8, 3], [100, 15], [5, 10, 23]]
Rows with K multiples : [[5, 10, 15], [100, 15]]