Python 程序:提取频率为偶数的行


当需要提取频率为偶数的矩阵的行时,一个 “all” 运算符和 “Counter” 方法的列表解析将被使用。

范例

以下是该范例的演示

Open Compiler
from collections import Counter my_list = [[41, 25, 25, 62], [41, 41, 41, 41, 22, 22], [65, 57, 65, 57], [11, 24, 36, 48]] print("The list is :") print(my_list) my_result = [sub for sub in my_list if all( value % 2 == 0 for key, value in list(dict(Counter(sub)).items()))] print("The result is :") print(my_result)

输出

The list is :
[[41, 25, 25, 62], [41, 41, 41, 41, 22, 22], [65, 57, 65, 57], [11, 24, 36, 48]]
The result is :
[[41, 41, 41, 41, 22, 22], [65, 57, 65, 57]]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个列表并显示在控制台上。

  • 使用列表解析来遍历列表中的元素,并使用 “all” 运算符检查该值是否可以被 2 整除。

  • 使用 “Counter” 和 “dict” 访问列表的元素。

  • 这被转换为一个列表并分配给一个变量。

  • 这显示为控制台上的输出。

更新于: 16-Sep-2021

177 查看

开启你的 职业生涯

完成课程获得认证

开始
广告