当前位置:首页>python>Python 30段代码提升开发效率,高效实用

Python 30段代码提升开发效率,高效实用

  • 2026-10-10 09:37:55
Python 30段代码提升开发效率,高效实用

在Python编程的世界里,简洁高效的代码往往能事半功倍。今天为大家整理了30个实用代码片段,覆盖日常开发中的高频场景,每个都短小精悍却威力无穷。

往期阅读>>>

Python 为什么会成为AI时代的头部语言

Python 40个常用的列表推导式

Python 50个提高代码开发效率的方法

Python 自动检测服务HTTPS证书过期时间并发送预警

Python 自动化操作Redis的15个实用脚本

Python 自动化管理Jenkins的15个实用脚本,提升效率

Python copyparty搭建轻量的文件服务器的方法

Python 实现2FA认证的方法,提升安全性

Python 封装20个常用API接口,提升开发效率

App2Docker:如何无需编写Dockerfile也可以创建容器镜像

Python 集成 Nacos 配置中心的方法

Python 35个JSON数据处理方法

Python 字典与列表的20个核心技巧

Python 15个文本分析的库,提升效率

Python 15个Pandas技巧,提升数据分析效率

Python 运维中30个常用的库,提升效率

Python调用远程接口的方法

Python 提取HTML文本的方法,提升效率

Python 应用容器化方法:实现“一次部署,处处运行”

Python 自动化识别Nginx配置并导出为excel文件,提升Nginx管理效率

Python 5个常见的异步任务处理框架

Python数据科学常见的30个库

Python 50个实用代码片段,优雅高效

1. 列表去重保持顺序

defremove_duplicates(lst):seen = set()return [xforxinlstifnot (xinseenorseen.add(x))]# 示例original = [3, 2, 1, 2, 3, 4, 5, 4]result = remove_duplicates(original)print(result)  # [3, 2, 1, 4, 5]

2. 字典键值反转

defreverse_dict(d):return {v: kfork, vind.items()}# 示例original = {'a': 1, 'b': 2, 'c': 3}reversed_dict = reverse_dict(original)print(reversed_dict)  # {1: 'a', 2: 'b', 3: 'c'}

3. 统计元素频率

fromcollectionsimportCounterdata = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']freq = Counter(data)print(freq.most_common(2))  # [('apple', 3), ('banana', 2)]

4. 检查字符串是否为数字

defis_number(s):try:float(s)returnTrueexceptValueError:returnFalse# 示例print(is_number("123.45"))  # Trueprint(is_number("abc"))     # False

5. 生成随机字符串

importrandomimportstringdefrandom_string(length=8):chars = string.ascii_letters+string.digitsreturn''.join(random.choice(chars) for_inrange(length))# 示例print(random_string(10))  # 类似 "aB3dE7gH9j"

6. 字符串首字母大写

defcapitalize_words(s):return' '.join(word.capitalize() forwordins.split())# 示例text = "hello world python"print(capitalize_words(text))  # "Hello World Python"

7. 读取文件行数

defcount_lines(filename):withopen(filename, 'r', encoding='utf-8') asf:returnsum(1for_inf)# 示例line_count = count_lines('data.txt')print(f"文件共有 {line_count} 行")

8. 批量重命名文件

importosdefbatch_rename(folder, prefix):fori, filenameinenumerate(os.listdir(folder), 1):old_path = os.path.join(folder, filename)new_name = f"{prefix}_{i}{os.path.splitext(filename)[1]}"new_path = os.path.join(folder, new_name)os.rename(old_path, new_path)

9. 计算日期差

fromdatetimeimportdatetimedefdays_between(date1, date2):d1 = datetime.strptime(date1, "%Y-%m-%d")d2 = datetime.strptime(date2, "%Y-%m-%d")returnabs((d2-d1).days)# 示例days = days_between("2024-01-01", "2024-03-20")print(f"相差 {days} 天")

10. 获取当前时间戳

importtimetimestamp = int(time.time())print(f"当前时间戳: {timestamp}")

11. 简单HTTP请求

importrequestsdeffetch_url(url):try:response = requests.get(url, timeout=5)returnresponse.status_code, response.text[:100]exceptrequests.RequestExceptionase:returnNone, str(e)# 示例status, content = fetch_url("https://httpbin.org/get")print(f"状态码: {status}")

12. 斐波那契数列(记忆化)

fromfunctoolsimportlru_cache@lru_cache(maxsize=None)deffibonacci(n):ifn<2:returnnreturnfibonacci(n-1) +fibonacci(n-2)# 示例print(fibonacci(10))  # 55

13. 快速排序实现

defquick_sort(arr):iflen(arr) <= 1:returnarrpivot = arr[len(arr)//2]left = [xforxinarrifx<pivot]middle = [xforxinarrifx == pivot]right = [xforxinarrifx>pivot]returnquick_sort(left) +middle+quick_sort(right)# 示例data = [3, 6, 8, 10, 1, 2, 1]sorted_data = quick_sort(data)print(sorted_data)  # [1, 1, 2, 3, 6, 8, 10]

14. 进度条显示

defprogress_bar(iteration, total, length=50):percent = (iteration/total)filled_length = int(length*percent)bar = '█'*filled_length+'-'* (length-filled_length)print(f'\r|{bar}| {percent:.1%}', end='\r')ifiteration == total:print()# 示例total_items = 100foriinrange(total_items+1):progress_bar(i, total_items)time.sleep(0.01)

15. 内存使用监控

importsysdefmemory_usage(obj):returnsys.getsizeof(obj)# 示例data_list = [iforiinrange(1000)]print(f"列表占用内存: {memory_usage(data_list)} 字节")

16. 邮箱格式验证

importredefis_valid_email(email):pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'returnbool(re.match(pattern, email))# 示例print(is_valid_email("test@example.com"))  # Trueprint(is_valid_email("invalid-email"))     # False

17. 密码强度检查

defcheck_password_strength(password):iflen(password) <8:return"弱"has_upper = any(c.isupper() forcinpassword)has_lower = any(c.islower() forcinpassword)has_digit = any(c.isdigit() forcinpassword)has_special = any(notc.isalnum() forcinpassword)score = sum([has_upper, has_lower, has_digit, has_special])ifscore == 4:return"强"elifscore>= 2:return"中"else:return"弱"

18. 多线程任务执行

importthreadingimporttimedefworker(name, delay):print(f"线程 {name} 开始")time.sleep(delay)print(f"线程 {name} 结束")# 示例threads = []foriinrange(3):t = threading.Thread(target=worker, args=(f"Thread-{i}", i+1))threads.append(t)t.start()fortinthreads:t.join()

19. 优雅的错误处理装饰器

defhandle_errors(func):defwrapper(*args, **kwargs):try:returnfunc(*args, **kwargs)exceptExceptionase:print(f"错误发生: {type(e).__name__}: {e}")returnNonereturnwrapper@handle_errorsdefrisky_operation(x, y):returnx/y# 示例result = risky_operation(10, 0)  # 输出: 错误发生: ZeroDivisionError: division by zero

20. JSON与Python对象互转

importjsondefsave_to_json(data, filename):withopen(filename, 'w', encoding='utf-8') asf:json.dump(data, f, ensure_ascii=False, indent=2)defload_from_json(filename):withopen(filename, 'r', encoding='utf-8') asf:returnjson.load(f)# 示例data = {"name": "张三", "age": 25, "skills": ["Python", "Java"]}save_to_json(data, "user.json")loaded_data = load_from_json("user.json")print(loaded_data)

21. 素数判断

defis_prime(n):ifn<2:returnFalseforiinrange(2, int(n**0.5) +1):ifn%i == 0:returnFalsereturnTrue# 示例print(is_prime(17))  # Trueprint(is_prime(20))  # False

22. 最大公约数计算

defgcd(a, b):whileb:a, b = b, a%breturna# 示例print(gcd(48, 18))  # 6

23. 中英文混合字符串长度计算

defmixed_string_length(s):chinese_count = sum(1forcinsif'\u4e00'<= c<= '\u9fff')english_count = len(s) -chinese_countreturnchinese_count*2+english_count# 示例text = "Hello世界Python编程"print(f"混合长度: {mixed_string_length(text)}")  # 20

24. 获取系统信息

importplatformdefsystem_info():info = {"系统": platform.system(),"版本": platform.version(),"处理器": platform.processor(),"Python版本": platform.python_version()    }returninfo# 示例print(system_info())

25. 图片尺寸获取

fromPILimportImagedefget_image_size(image_path):withImage.open(image_path) asimg:returnimg.size# 示例width, height = get_image_size("example.jpg")print(f"图片尺寸: {width}x{height}")

26. SQLite简单操作

importsqlite3defcreate_db():conn = sqlite3.connect('example.db')cursor = conn.cursor()cursor.execute('''CREATE TABLE IF NOT EXISTS users                     (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')conn.commit()conn.close()

27. 提取网页链接

importredefextract_urls(text):pattern = r'https?://[^\s<>"]+|www\.[^\s<>"]+'returnre.findall(pattern, text)# 示例html = '访问 <a href="https://www.example.com">示例网站</a> 和 http://test.com'urls = extract_urls(html)print(urls)  # ['https://www.example.com', 'http://test.com']

28. ZIP文件处理

importzipfiledefzip_files(files, zipname):withzipfile.ZipFile(zipname, 'w') aszipf:forfileinfiles:zipf.write(file)defunzip_file(zipname, extract_to):withzipfile.ZipFile(zipname, 'r') aszipf:zipf.extractall(extract_to)

29. 函数执行时间测量

importtimedeftimer(func):defwrapper(*args, **kwargs):start = time.perf_counter()result = func(*args, **kwargs)end = time.perf_counter()print(f"{func.__name__} 执行时间: {end - start:.6f}秒")returnresultreturnwrapper@timerdefslow_function():time.sleep(1)return"完成"# 示例slow_function()

30. 简单数据标准化

defnormalize_data(data):min_val = min(data)max_val = max(data)return [(x-min_val) / (max_val-min_val) forxindata]# 示例original = [10, 20, 30, 40, 50]normalized = normalize_data(original)print(normalized)  # [0.0, 0.25, 0.5, 0.75, 1.0]

这30个Python代码片段涵盖了从基础到进阶的多个应用场景,力求在最短的代码中实现最大的功能。掌握这些技巧不仅能提升编程效率,还能写出更优雅、更Pythonic的代码。

如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
“无他,惟手熟尔”!有需要的用起来!

想高效学习Python?下面三本精选好书满足你的不同需求!

《流畅的Python(第2版)》——Python进阶必读!深入讲解高级特性与最佳实践,适合想精进的开发者。

《Python从新手到高手》:初学者首选,系统学习全栈技能。

《Python数据分析:从零基础入门到案例实战》——数据科学利器!手把手教你用Python处理数据,实战案例学完就能用。

三本书均支持先用后付、运费险和7天无理由退货,放心购买!点击“购买”按钮,立即开启你的Python学习之旅吧!

▼点击下方,即可购书
------加入知识库与更多人一起学习------

https://ima.qq.com/wiki/?shareId=f2628818f0874da17b71ffa0e5e8408114e7dbad46f1745bbd1cc1365277631c

最新文章

随机文章