python中统计次数的函数
时间: 2024-05-05 09:20:02 浏览: 17
在Python中,可以使用`collections`模块中的`Counter`类来统计元素出现的次数。具体实现如下:
```python
from collections import Counter
lst = [1, 2, 3, 1, 2, 1, 4, 5, 4, 3, 2]
count = Counter(lst)
print(count)
```
输出结果为:
```
Counter({1: 3, 2: 3, 3: 2, 4: 2, 5: 1})
```
其中,`count`是一个`Counter`对象,它的键是出现的元素,值是该元素出现的次数。
相关问题
统计python函数调用次数
可以使用装饰器来统计Python函数的调用次数。下面是一个例子:
```python
def count_calls(func):
def wrapper(*args, **kwargs):
wrapper.num_calls += 1
return func(*args, **kwargs)
wrapper.num_calls = 0
return wrapper
@count_calls
def my_func():
print("Hello, world!")
my_func()
my_func()
print(my_func.num_calls)
```
输出:
```
Hello, world!
Hello, world!
2
```
在这个例子中,我们定义了一个装饰器 `count_calls` ,它接受一个函数作为参数,并返回一个新的函数 `wrapper` 。`wrapper` 函数使用一个变量 `num_calls` 来记录函数被调用的次数,并在每次调用时递增它。最后,装饰器返回的函数 `wrapper` 成为了原始函数的新版本。
在上面的例子中,我们将 `count_calls` 装饰器应用到了函数 `my_func` 上。当我们调用 `my_func` 两次时,`num_calls` 变量的值会分别递增为 1 和 2。最后,我们输出了 `my_func.num_calls` 的值,它应该等于 2。
python列表中次数统计
可以使用Python中的collections模块中的Counter函数来统计列表中元素出现的次数。具体操作如下:
1. 导入collections模块
```python
import collections
```
2. 定义列表
```python
lst = [1, 2, 3, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 7, 8, 9]
```
3. 使用Counter函数统计元素出现的次数
```python
count = collections.Counter(lst)
```
4. 输出结果
```python
print(count)
```
输出结果为:
```
Counter({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2})
```
其中,Counter函数返回的是一个字典,字典的键为列表中的元素,值为该元素在列表中出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)