Python 中匹配特定条件的元素数量

pythonserver side programmingprogramming更新于 2026/1/22 14:36:17

在本文中,我们将了解如何从 Python 列表中获取一些选定的元素。因此,我们需要设计一些条件,并且只应选择满足该条件的元素并打印它们的计数。

使用 in 和 sum

在这种方法中,我们使用 in 条件来选择元素并使用一些来获取它们的计数。如果元素存在,则使用 1,否则使用 0 作为 in 条件的结果。

示例

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# 给定列表
print("给定列表:\n", Alist)
cnt = sum(1 for i in Alist if i in('Mon','Wed'))
print("Number of times the condition is satisfied in the list:\n",cnt)

输出

运行上述代码得到以下结果 −

给定列表:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Number of times the condition is satisfied in the list:
3

使用 map 和 lambda

这里也用到了条件,但也使用了 lambda 和 map 函数。最后我们应用 sum 函数来获取计数。

示例

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# 给定列表
print("给定列表:\n", Alist)
cnt=sum(map(lambda i: i in('Mon','Wed'), Alist))
print("Number of times the condition is satisfied in the list:\n",cnt)

输出

运行上述代码得到以下结果 −

给定列表:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Number of times the condition is satisfied in the list:
3

使用 reduce

reduce函数将特定函数应用于作为参数提供给它的列表中的所有元素。我们将其与in条件一起使用,最终产生符合条件的元素数量。

示例

from functools import reduce
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# 给定列表
print("给定列表:\n", Alist)
cnt = reduce(lambda count, i: count + (i in('Mon','Wed')), Alist, 0)
print("Number of times the condition is satisfied in the list:\n",cnt)

输出

运行上述代码得到以下结果 −

给定列表:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Number of times the condition is satisfied in the list:
3

相关文章


有用资源