在Python中,统计输出的结果可以通过多种方法实现,以下是一些常见的方法:
1. 使用`for`循环和`if`语句:
a = 'dsjlfaldsnvmfgahjgdjkafhkajfhuihvkdjvk'
b = 0
for i in a:
if i == 'd':
b += 1
print(b) 输出:6
2. 使用字典来统计数字出现的个数:
def count_numbers(numbers):
count_dict = {}
for num in numbers:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
return count_dict
numbers = [1, 2, 3, 4, 1, 2, 3, 4, 5]
result = count_numbers(numbers)
print(result) 输出:{1: 2, 2: 2, 3: 2, 4: 2, 5: 1}
3. 使用`count()`方法:
T = (123, 'Google', 'Runoob', 'Taobao', 123)
print("123 元素个数:", T.count(123))
print("Runoob 元素个数:", T.count('Runoob'))
4. 使用`collections.Counter`类:
from collections import Counter
my_list = [1, 2, 3, 2, 1, 2, 3, 4]
c = Counter(my_list)
print(c) 输出:Counter({1: 2, 2: 3, 3: 2, 4: 1})
5. 使用`defaultdict`:
from collections import defaultdict
lists = ['a', 'a', 'b', 5, 6, 7, 5]
count_dict = defaultdict(int)
for item in lists:
count_dict[item] += 1
print(count_dict) 输出:defaultdict(
, {'a': 2, 'b': 1, 5: 2, 6: 1, 7: 1})
6. 使用`numpy`库计算描述性统计值:
import numpy as np
data = [10, 20, 30, 40, 50]
mean = np.mean(data)
print("平均值:", mean)
median = np.median(data)
print("中位数:", median)
7. 使用`statistics`库计算众数:
from statistics import mode
data = [10, 20, 30, 20, 50, 20]
mode_value = mode(data)
print("众数:", mode_value)