本文共 3189 字,大约阅读时间需要 10 分钟。
Python3 的功能强大,学习一些实用的技巧可以让你的代码更高效、更简洁。以下 30 个技巧将帮助你提升编程效率。
Python2 已于 2020 年 1 月 1 日正式弃用,建议全面升级到 Python3。很多教程和库都只支持 Python3,继续使用 Python2 可能会遇到兼容性问题。
在运行脚本前,检查当前环境的 Python 版本。可以用以下代码:
import sysprint("当前 Python 版本:", sys.version) IPython 是 Python 的交互式解释器,功能强大:
%cd:切换目录%edit:打开编辑器并直接执行代码%env:显示环境变量%pip install [包名]:在线安装包%time 和 %timeit:代码性能测试安装 IPython:
pip3 install ipython
使用列表表达式生成列表,代码简洁高效:
[expression for item in list if condition]
例如:
# 生成 1-100 的整数列表numbers = [x for x in range(1, 101)]
查看对象占用内存的大小:
import syssys.getsizeof(object)
注意:range 类型占用的内存比普通列表小。
Python 函数可以返回多个值,直接用元组:
def get_multiple RETURNS: return 1, 2, 3
数据类提供了方便的数据操作:
__eq__,支持对象比较__repr__,方便调试示例:
from dataclasses import dataclass@dataclassclass User: name: str age: int
使用 swap 技巧:
a, b = b, a
只需一行代码交换变量。
合并字典简单高效:
# 创建新字典,将原字典的键值覆盖new_dict = {**dict1, **dict2} 使用 title() 方法:
"hello world".title() # "Hello World"
按空格分割字符串:
"hello world python".split() # ['hello', 'world', 'python']
使用 join 方法:
" ".join(["hello", "world"]) # "hello world"
安装 emoji 模块:
pip3 install emoji
示例:
from emoji import emojiprint(emoji("Hello🌍")) # "Hello🌍" Python 切片简单灵活:
list[start:stop:step]
默认参数:
示例:
numbers = list(range(10))numbers[2:7:2] # [4, 6, 8]
使用负步长:
"hello".[::-1] # "olleh"numbers = list(range(10))numbers[::-1] # [9, 8, 7, ..., 0]
安装 Pillow:
pip3 install Pillow
示例:
from PIL import Imageimg = Image.open("kittens.jpg")img.show() 将函数应用到可迭代对象:
list(map(func, iterable))
示例:
names = ["Alice", "Bob", "Charlie"]sorted_names = list(map(str.upper, names))# ["ALICE", "BOB", "CHARLIE"]
使用 set():
unique_elements = set(list_or_string)
统计字符或列表中出现次数最多的值:
def find_maxFrequency(lst): if not lst: return None frequency = {} for item in lst: frequency[item] = lst.count(item) max_count = max(frequency.values()) max_items = [k for k, v in frequency.items() if v == max_count] return max_items 安装 Progress:
pip3 install progress
示例:
from progress import Progressp = Progress()p.update("下载中...", 50)p.update("下载完成!", 100) 在 IPython 中,_ 表示上一条命令的输出:
In [1]: 3 * 3Out[1]: 9In [2]: _
python3 -m http.server
使用 triple quotes:
text = """这是一长多行的字符串."""
使用三元运算符:
value = "成功!" if condition else "失败!"
使用 collections.Counter:
from collections import Countercounts = Counter(list)
a > b > c > d
支持多个比较操作。
安装 Colorama:
pip3 install colorama
示例:
from colorama import Fore, Back, Styleprint(Fore.RED + "警告" + Style.RESET_ALL)
安装:
pip3 install python-dateutil
示例:
from dateutil import parserdate = parser.parse("2024-05-20") Python3 中除号默认返回浮点数,// 返回整数:
# Python35 / 2 # 2.55 // 2 # 2
安装:
pip3 install chardet
示例:
from chardet import detecttext = "测试文本"detected_char = detect(text)[0]
这些技巧可以帮助你提升代码的效率和可读性,欢迎在实际项目中灵活运用!
转载地址:http://lklfk.baihongyu.com/