Python 小代码,大作用18
Python 以其简洁、易读和丰富的库而闻名,使其成为各种应用的理想选择。以下是 1500 个左右的 Python 小代码片段,涵盖了广泛的主题,从列表处理到 web 编程,再到科学计算。
列表处理
1. 创建一个不重复元素列表
```python
my_list = list(set(my_list))
```
2. 扁平化嵌套列表
```python
flat_list = [item for sublist in my_list for item in sublist]
```
3. 按特定键对列表进行排序
```python
(key=lambda x: x['key'])
```
字符串操作
4. 从字符串中删除空白
```python
my_string = ()
```
5. 将字符串转换为大写/小写
```python
my_string = () / ()
```
6. 查找字符串中的子字符串
```python
if 'substring' in my_string:
# 子字符串存在
```
字典处理
7. 创建一个键大小写不敏感的字典
```python
my_dict = dict(((), v) for k, v in ())
```
8. 将字典中的键转换为元组
```python
my_keys = tuple(())
```
9. 从字典中获取默认值
```python
my_value = ('my_key', 'default_value')
```
函数
10. 创建一个带有默认参数值的函数
```python
def my_function(arg1, arg2=None):
# arg2 具有默认值 None
```
11. 创建一个可变长参数函数
```python
def my_function(*args):
# args 是一个包含所有传递参数的元组
```
12. 创建一个返回多个值的函数
```python
def my_function():
return 1, 2, 3
```
文件处理
13. 读取一个文件并返回其内容
```python
with open('', 'r') as f:
contents = ()
```
14. 将数据写入一个文件
```python
with open('', 'w') as f:
('Hello, world!')
```
15. 逐行迭代一个文件
```python
with open('', 'r') as f:
for line in f:
# 对每一行操作
```
web 编程
16. 发送一个 GET 请求
```python
import requests
response = ('')
```
17. 发送一个 POST 请求
```python
import requests
response = ('', data={'key': 'value'})
```
18. 解析 HTML 页面
```python
from bs4 import BeautifulSoup
html = BeautifulSoup(page_content, '')
```
科学计算
19. 计算圆周率
```python
import math
pi =
```
20. 求矩阵的行列式
```python
import numpy as np
A = ([[1, 2], [3, 4]])
det = (A)
```
21. 绘制一个图形
```python
import as plt
([1, 2, 3], [4, 5, 6])
()
```
其他
22. 计时一个代码块的运行
```python
import time
start = ()
# 执行代码块
end = ()
duration = end - start
```
23. 查找一个字符串中的最长公共子序列
```python
def lcs(s1, s2):
m = len(s1)
n = len(s2)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif s1[i - 1] == s2[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[-1][-1]
```
24. 生成随机数
```python
import random
() # 生成 [0, 1) 之间的随机浮点数
(1, 10) # 生成 [1, 10] 之间的随机整数
```
2024-10-18
Python自动化Excel:高效保存数据到XLSX文件的终极指南
https://www.shuihudhg.cn/134161.html
Java方法注释深度指南:从基础到高级,构建清晰可维护的代码文档
https://www.shuihudhg.cn/134160.html
驾驭Python长字符串:从多行定义到转义字符与特殊用法深度解析
https://www.shuihudhg.cn/134159.html
PHP获取当前月初日期与时间戳:多种高效方法详解与最佳实践
https://www.shuihudhg.cn/134158.html
PHP与AJAX图片上传:实现动态图像处理与预览的完整指南
https://www.shuihudhg.cn/134157.html
热门文章
Python 格式化字符串
https://www.shuihudhg.cn/1272.html
Python 函数库:强大的工具箱,提升编程效率
https://www.shuihudhg.cn/3366.html
Python向CSV文件写入数据
https://www.shuihudhg.cn/372.html
Python 静态代码分析:提升代码质量的利器
https://www.shuihudhg.cn/4753.html
Python 文件名命名规范:最佳实践
https://www.shuihudhg.cn/5836.html