📜  用偶数频率元素提取矩阵行的Python程序

📅  最后修改于: 2022-05-13 01:55:31.864000             🧑  作者: Mango

用偶数频率元素提取矩阵行的Python程序

给定一个矩阵,任务是编写一个Python程序来提取所有元素频率为偶数的行。

例子:

方法 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))


输出:

方法 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))

输出: