用偶数频率元素提取矩阵行的Python程序
给定一个矩阵,任务是编写一个Python程序来提取所有元素频率为偶数的行。
例子:
Input: [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2], [6, 5, 6, 5], [1, 2, 3, 4]]
Output: [[4, 4, 4, 4, 2, 2], [6, 5, 6, 5]]
Explanation:
- frequency of 4-> 4 which is even
- frequency of 2-> 2 which is even
- frequency of 6-> 2 which is even
- frequency of 5-> 2 which is even
方法 1:使用列表理解、 Counter()和all()
其中,count 使用 Counter() 进行维护,all() 用于检查所有频率是否为偶数,如果不是,则不会在结果列表中输入行。
程序:
Python3
from collections import Counter
# initializing list
test_list = [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2],
[6, 5, 6, 5], [1, 2, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# Counter() gets the required frequency
res = [sub for sub in test_list if all(
val % 2 == 0 for key, val in list(dict(Counter(sub)).items()))]
# printing result
print("Filtered Matrix ? : " + str(res))
Python3
from collections import Counter
# initializing list
test_list = [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2],
[6, 5, 6, 5], [1, 2, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# Counter() gets the required frequency
# filter() used to perform filtering
res = list(filter(lambda sub: all(val % 2 == 0 for key,
val in list(dict(Counter(sub)).items())), test_list))
# printing result
print("Filtered Matrix ? : " + str(res))
输出:
The original list is : [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2], [6, 5, 6, 5], [1, 2, 3, 4]]
Filtered Matrix ? : [[4, 4, 4, 4, 2, 2], [6, 5, 6, 5]]
方法 2:使用filter() 、 Counter()和 items()
与上述方法类似,不同之处在于 filter() 和 lambda函数用于过滤偶数行的任务。
程序:
蟒蛇3
from collections import Counter
# initializing list
test_list = [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2],
[6, 5, 6, 5], [1, 2, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# Counter() gets the required frequency
# filter() used to perform filtering
res = list(filter(lambda sub: all(val % 2 == 0 for key,
val in list(dict(Counter(sub)).items())), test_list))
# printing result
print("Filtered Matrix ? : " + str(res))
输出:
The original list is : [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2], [6, 5, 6, 5], [1, 2, 3, 4]]
Filtered Matrix ? : [[4, 4, 4, 4, 2, 2], [6, 5, 6, 5]]