numpy库常用函数
python中统计次数的方法(出现次数总数)
在Python中,有多种方法可以统计次数,包括出现次数和总数。下面将介绍几种常用的统计方法。
1. count(方法:
count(方法是Python中内置的方法之一,用于统计指定元素在列表、字符串、元组等中出现的次数。例如:
```python
lst = [1, 2, 3, 1, 4, 1]
count = unt(1)
print(count)  # 输出:3
string = "Hello, World!"
count = unt("o")
print(count)  # 输出:2
tpl = (1, 2, 3, 1, 4, 1)
count = unt(1)
print(count)  # 输出:3
```
2. collections.Counter类:
Counter类是collections模块中的一个类,用于统计可哈希对象的出现次数。它可以接收一个可迭代对象作为输入,并返回一个字典,其中包含了每个元素以及其出现的次数。例如:
```python
from collections import Counter
lst = [1, 2, 3, 1, 4, 1]
counter = Counter(lst)
print(counter)  # 输出:Counter({1: 3, 2: 1, 3: 1, 4: 1})
string = "Hello, World!"
counter = Counter(string)
print(counter)  # 输出:Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1})
tpl = (1, 2, 3, 1, 4, 1)
counter = Counter(tpl)
print(counter)  # 输出:Counter({1: 3, 2: 1, 3: 1, 4: 1})
```
3.使用字典统计次数:
可以使用字典来统计元素的出现次数。遍历可迭代对象,对于每个元素,将其作为字典的键,出现的次数作为字典的值。例如:
```python
lst = [1, 2, 3, 1, 4, 1]
count_dict = {}
for num in lst:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
print(count_dict)  # 输出:{1: 3, 2: 1, 3: 1, 4: 1}
string = "Hello, World!"
count_dict = {}
for char in string:
if char in count_dict:
count_dict[char] += 1
else:
count_dict[char] = 1
print(count_dict)  # 输出:{'H': 1, 'e': 1, 'l': 3, 'o': 2, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}
tpl = (1, 2, 3, 1, 4, 1)
count_dict = {}
for num in tpl:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
print(count_dict)  # 输出:{1: 3, 2: 1, 3: 1, 4: 1}
```
4. 使用numpy库统计总数:
如果要统计列表、数组等中的元素总数,可以使用numpy库的sum(函数。该函数可以接受一个数组作为输入,并返回所有元素的和。例如:
```python
import numpy as np
lst = [1, 2, 3, 4, 5]
total = np.sum(lst)
print(total)  # 输出:15
arr = np.array([[1, 2, 3], [4, 5, 6]])
total = np.sum(arr)
print(total)  # 输出:21
```
除了sum(函数外,numpy库还提供了其他一些统计函数,例如mean(计算平均值,max(计算最大值,min(计算最小值等。
综上所述,以上是Python中统计次数的几种常用方法,包括使用count(方法、collections.Counter类、字典以及numpy库。这些方法可以根据具体的需求灵活选择,并根据不同场景的特点选择相应的方法来进行统计。