符合Python中特定条件的元素计数
在本文中,我们将看到如何从Python列表中获取一些选定的元素。因此,我们需要设计一些条件,并且仅应选择满足该条件的元素并打印其计数。
求和
在这种方法中,我们有条件地选择元素并使用一些元素来获取它们的数量。如果元素存在,则使用1;否则,条件条件的结果使用0。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:\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)输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3
有映射和lambda
这里也可以使用条件,但也可以使用lambda和map函数。最后,我们应用求和函数来获取计数。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:\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)输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3
与减少
reduce函数将特定函数应用于作为参数提供给它的列表中的所有元素。我们将其与in条件一起使用,最终生成与该条件匹配的元素计数。
示例
from functools import reduce
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:\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)输出结果
运行上面的代码给我们以下结果-
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied in the list: 3
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短