打印所有元素频率大于 K 的行的Python程序
给定矩阵,提取所有元素频率大于 K 的所有行。
Input : test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]], K = 2
Output : [[1, 1, 1, 1]]
Explanation : Here, frequency of 1 is 4 > 2, hence row retained.
Input : test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 3, 4, 1], [4, 5, 6, 8]], K = 2
Output : []
Explanation : No list filtered as result.
方法 #1:使用列表理解+ all() + count()
在这里,我们使用列表推导来执行遍历元素的任务,并且 all() 用于检查使用 count() 提取的每个元素 count()。
Python3
# Python3 code to demonstrate working of
# Rows with all Elements frequency greater than K
# Using list comprehension + count() + all()
def freq_greater_K(row, K) :
# checking for all elements occurrence greater than K
return all(row.count(ele) > K for ele in row)
# initializing list
test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# checking for each row
res = [ele for ele in test_list if freq_greater_K(ele, K)]
# printing result
print("Filtered rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Rows with all Elements frequency greater than K
# Using filter() + lambda + all() + count()
def freq_greater_K(row, K) :
# checking for all elements occurrence greater than K
return all(row.count(ele) > K for ele in row)
# initializing list
test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# checking for each row
res = list(filter(lambda ele : freq_greater_K(ele, K), test_list))
# printing result
print("Filtered rows : " + str(res))
输出:
The original list is : [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]]
Filtered rows : [[1, 1, 2, 3, 2, 3], [1, 1, 1, 1]]
方法 #2:使用filter() + lambda + all() + count()
在这里,过滤任务是使用 filter() + lambda 完成的,all() 用于检查每个元素,count() 用于计算计数。
蟒蛇3
# Python3 code to demonstrate working of
# Rows with all Elements frequency greater than K
# Using filter() + lambda + all() + count()
def freq_greater_K(row, K) :
# checking for all elements occurrence greater than K
return all(row.count(ele) > K for ele in row)
# initializing list
test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# checking for each row
res = list(filter(lambda ele : freq_greater_K(ele, K), test_list))
# printing result
print("Filtered rows : " + str(res))
输出:
The original list is : [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]]
Filtered rows : [[1, 1, 2, 3, 2, 3], [1, 1, 1, 1]]