符合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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短