如何用函数写符合任一条件计个数
- 编程技术
- 2025-02-02 18:48:21
- 1
```pythondef count_if(lst, condition : return sum(1 for item in lst if condition(ite...
```python
def count_if(lst, condition):
return sum(1 for item in lst if condition(item))
示例使用
定义一个条件函数,比如我们想要计算列表中所有大于5的元素个数
def is_greater_than_five(x):
return x > 5
定义一个列表
numbers = [1, 2, 6, 3, 8, 4, 10]
调用函数并打印结果
count = count_if(numbers, is_greater_than_five)
print(count) 输出应该是 4,因为有4个数字大于5
```
本文由夕逆IT于2025-02-02发表在夕逆IT,如有疑问,请联系我们。
本文链接:http://xinin56.com/bian/435160.html
本文链接:http://xinin56.com/bian/435160.html
上一篇:当兵学坦克维修,以后有什么出息
下一篇:连字加什么偏旁