这些案例将涵盖数据处理、算法、文件操作、数据可视化、网络编程、机器学习等多个领域.
以下是具体的操作步骤和示例代码:
基础操作
1. 计算两个数的和
def add(a, b):
return a + b
print(add(3, 5))
2. 判断一个数是否为偶数
def is_even(n):
return n % 2 == 0
print(is_even(4))
3. 计算列表中所有数的平均值
def average(lst):
return sum(lst) / len(lst)
print(average([1, 2, 3, 4, 5]))
4. 反转字符串
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
数据处理
5. 读取CSV文件
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())
6. 写入CSV文件
df.to_csv('output.csv', index=False)
7. 处理缺失值
df.fillna(df.mean(), inplace=True)
8. 数据分组和聚合
grouped = df.groupby('category').sum()
print(grouped)
算法
9. 冒泡排序
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))
10. 二分查找
def binary_search(arr, x):
l, r = 0, len(arr) - 1
while l <= r:
mid = (l + r) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1
print(binary_search([1, 2, 3, 4, 5, 6, 7], 4))
11. 斐波那契数列
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
fibs = [0, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
print(fibonacci(10))
12. 求阶乘
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
文件操作
13. 读取文本文件
with open('file.txt', 'r') as file:
content = file.read()
print(content)
14. 写入文本文件
with open('output.txt', 'w') as file:
file.write("Hello, world!")
15. 文件复制
def copy_file(src, dest):
with open(src, 'r') as f_src:
content = f_src.read()
with open(dest, 'w') as f_dest:
f_dest.write(content)
copy_file('file.txt', 'copy.txt')
数据可视化
16. 绘制折线图
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('折线图')
plt.show()
17. 绘制柱状图
plt.bar(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('柱状图')
plt.show()
18. 绘制散点图
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('散点图')
plt.show()
19. 绘制饼图
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('饼图')
plt.show()
统计分析
20. 计算均值和标准差
import numpy as np
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
mean = np.mean(data)
std_dev = np.std(data)
print(f'均值: {mean}, 标准差: {std_dev}')
21. 计算相关系数
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
correlation = np.corrcoef(x, y)[0, 1]
print(f'相关系数: {correlation}')
22. 线性回归
from sklearn.linear_model import LinearRegression
x = np.array(x).reshape(-1, 1)
y = np.array(y)
model = LinearRegression().fit(x, y)
print(f'截距: {model.intercept_}, 斜率: {model.coef_[0]}')
网络编程
23. 发送HTTP请求
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.json())
24. 创建一个简单的HTTP服务器
from http.server import SimpleHTTPRequestHandler, HTTPServer
Def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
print('Starting httpd...')
httpd.serve_forever()
run()
机器学习
25. 训练和预测线性回归模型
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
model = LinearRegression().fit(X_train, y_train)
predictions = model.predict(X_test)
print(predictions)
26. K近邻分类
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
predictions = knn.predict(X_test)
print(predictions)
深度学习
27. 创建一个简单的神经网络
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
Dense(64, activation='relu'),
Dense(1)
])
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, y_train, epochs=10, batch_size=32)
28. 预测新数据
predictions = model.predict(X_test)
print(predictions)
自然语言处理
29. 词频统计
from collections import Counter
import re
text = "Hello world! Hello everyone. This is a test."
words = re.findall(r'\w+', text.lower())
word_counts = Counter(words)
print(word_counts)
30. 词云生成
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wc = WordCloud(width=800, height=400).generate_from_frequencies(word_counts)
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
温馨提示:更多项目代码打包好了,文件夹领取在,
面向对象编程
31. 创建类和对象
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f'{self.name} says woof!')
my_dog = Dog('Buddy', 3)
my_dog.bark()
32. 继承和多态
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return f'{self.name} says woof!'
class Cat(Animal):
def speak(self):
return f'{self.name} says