1. 使用`for`循环和`if`语句:
```python
a = 'dsjlfaldsnvmfgahjgdjkafhkajfhuihvkdjvk'
b = 0
for i in a:
if i == 'd':
b += 1
print(b) 输出:3
2. 使用`count()`函数:
```python
my_list = [1, 2, 3, 2, 1, 2, 3, 4]
count = my_list.count(2)
print(count) 输出:3
my_string = 'hello world'
count = my_string.count('l')
print(count) 输出:3
3. 使用`collections.Counter`类:
```python
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})
my_string = 'hello world'
c = Counter(my_string)
print(c['l']) 输出:3
4. 使用`os`模块统计文件夹下文件个数:
```python
import os
def count_files(directory):
count = 0
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
count += 1
return count
folder_path = '/path/to/folder' 替换为实际的文件夹路径
file_count = count_files(folder_path)
print('文件夹中的文件个数为:', file_count)
5. 使用`NumPy`和`SciPy`库进行数值分析:
```python
from numpy import array
from scipy import stats
data = array([1, 2, 3, 4, 5])
mean = stats.mean(data)
median = stats.median(data)
mode = stats.mode(data)
range_val = stats.tstd(data)
variance = stats.var(data)
std_dev = stats.stdev(data)
z_scores = stats.zscore(data)
correlation = stats.corrcoef(data, data)
6. 使用`collections.Counter`类统计代码行数:
```python
from collections import Counter
def count_code_lines(path):
comments = 0
blanks = 0
codes = 0
with open(path, encoding='utf-8') as f:
for line in f.readlines():
line = line.strip()
if line == '':
blanks += 1
elif line.startswith(''):
comments += 1
else:
codes += 1
return comments, blanks, codes
以上方法可以帮助你实现基本的统计功能。根据你的具体需求,你可以选择合适的方法进行操作