python中满足条件相加_符合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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值