当前位置:首页 > 编程技术 > 正文

如何用函数写符合任一条件计个数

如何用函数写符合任一条件计个数

```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

```

最新文章