30个python常用代码大全
时间: 2024-06-19 19:01:26 浏览: 252
Python是一门功能强大的编程语言,拥有丰富的标准库和社区支持。这里列举了30个Python中的常用代码片段,涵盖了基础操作到高级功能:
1. **打印Hello, World!**: `print("Hello, World!")`
2. **变量声明**: `name = "John Doe"`
3. **数据类型**(整型、浮点型、字符串、列表、元组、字典):
- `int_value = 10`
- `float_value = 3.14`
- `str_value = "Hello"`
- `list_value = [1, 2, 3]`
- `tuple_value = (4, 5, 6)`
- `dict_value = {"name": "Alice", "age": 25}`
4. **条件语句**: `if condition: ... else: ...`
5. **循环结构**(for、while):
- `for item in list: print(item)`
- `while condition: ...`
6. **函数定义**: `def function_name(parameters): ...`
7. **异常处理**: `try: ... except ExceptionType: ...`
8. **列表推导式**: `[expression for item in iterable]`
9. **字典推导式**: `{key: expression for item in iterable}`
10. **生成器表达式**: `(expression for item in iterable)`
11. **切片操作**: `list[start:end:step]`
12. **排序操作**: `list.sort()`
13. **文件操作**: `with open('file.txt', 'r') as file: content = file.read()`
14. **模块导入**: `import module_name`
15. **装饰器**: `@decorator_function`
16. **lambda函数**: `lambda arguments: expression`
17. **Pandas数据处理**: `import pandas as pd; df = pd.read_csv('data.csv')`
18. **NumPy数组操作**: `import numpy as np; array = np.array([1, 2, 3])`
19. **Matplotlib绘图**: `import matplotlib.pyplot as plt; plt.plot([1, 2, 3])`
20. **requests库**: `response = requests.get('https://api.example.com/data')`
21. **正则表达式**: `import re; pattern = r'\d+'; match = re.search(pattern, '123abc')`
22. **BeautifulSoup解析HTML**: `from bs4 import BeautifulSoup; soup = BeautifulSoup(html)`
23. **异步编程**: `async def function(): ...`
24. **多线程或多进程**: `import threading; threads = [threading.Thread(target=func) for _ in range(n)]`
25. **装饰器延迟执行**: `functools.lru_cache(maxsize=100)`
26. **上下文管理器**: `with context_manager: ...`
27. **列表合并**: `result = list1 + list2`
28. **zip函数**: `zipped = zip(list1, list2)`
29. **递归**: `def factorial(n): return n * factorial(n-1) if n > 1 else 1`
30. **迭代器**: `iterable = iter(range(10)); next_value = next(iterable)`
阅读全文