Python高效编程:22个实用技巧与代码示例

月亮慢半拍
月亮慢半拍
发布时间:2026-10-13 | 6人浏览过
原创

本文整理了22个Python编程实用技巧,涵盖变量交换、条件判断、字符串处理、内存优化及调试方法。通过具体代码示例,展示如何利用Python特性简化逻辑、提升执行效率并优化资源使用,帮助开发者写出更简洁高效的代码。

1. 原地交换两个数字

Python 提供了一种简洁的方式,在一行代码中完成赋值与变量值的交换。具体实现如下:

x,y= 10,20
print(x,y)
x,y= y,x
print(x,y)
#1 (10, 20)
#2 (20, 10)

赋值语句右侧会创建一个新的元组,左侧则立即对该元组进行解包(unpack),将值分别赋给变量 <a> 和 <b>。

赋值完成后,新生成的元组不再被引用,随即被标记为可垃圾回收,从而完成了变量值的交换。

2. 链状比较操作符

将多个比较操作符连接起来使用,是另一个非常便捷的技巧:

n= 10
result= 1< n< 20
print(result)
# True
result= 1> n<= 9
print(result)
# False

3. 使用三元操作符来进行条件赋值

三元操作符是 if-else 语句(即条件操作符)的简写形式:

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]

以下示例展示了如何利用三元操作符使代码更加紧凑简洁。例如,若 y 等于 9,则将 x 赋值为 10,否则赋值为 20。当然,你也可以根据需要扩展这种操作链。

x = 10 if (y == 9) else 20

同样地,这种操作也可以应用于类的实例化:

x = (classA if y == 1 else classB)(param1, param2)

在上述示例中,classA 与 classB 代表两个不同的类,根据条件调用其中一个类的构造函数。

另一个示例展示了如何链接多个条件表达式来计算最小值:

def small(a,b,c):
returnaifa<= banda<= celse(bifb<= aandb<= celsec)
print(small(1,0,1))
print(small(1,2,2))
print(small(2,2,3))
print(small(5,4,3))
#Output
#0 #1 #2 #3

我们甚至可以在列表推导式中使用三元运算符:

[m**2 if m > 10 else m**4 for m in range(50)]
#=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

4. 多行字符串

基本的方法是使用源自 C 语言的反斜杠:

multiStr= “select * from multi_row
where row_id < 5”
print(multiStr)
# select * from multi_row where row_id < 5

另一种技巧是使用三引号:

multiStr= “””select * from multi_row
where row_id < 5″””
print(multiStr)
#select * from multi_row
#where row_id < 5

上述方法共同存在的问题是缩进处理不当会在字符串中引入多余空格。因此,更优的解决方案是将字符串拆分为多行,并将整个字符串包裹在括号中:

multiStr= (“select * from multi_row ”
“where row_id < 5 ”
“order by age”)
print(multiStr)
#select * from multi_row where row_id < 5 order by age

5. 存储列表元素到新的变量中

我们可以利用列表来初始化多个变量。在解包列表时,变量的数量必须严格等于列表中的元素数量,否则将引发错误。

testList= [1,2,3]
x,y,z= testList
print(x,y,z)
#-> 1 2 3

6. 打印引入模块的文件路径

如果你需要查询代码中引用的模块的绝对路径,可以使用以下技巧:

import threading
import socket
print(threading)
print(socket)
#1- <module ‘threading' from ‘/usr/lib/python2.7/threading.py'>
#2- <module ‘socket' from ‘/usr/lib/python2.7/socket.py'>

7. 交互环境下的 “_” 操作符

这是一个鲜为人知但非常实用的特性。在 Python 控制台(REPL)中,无论何时测试表达式或调用方法,其结果都会被自动分配给一个临时变量:_(下划线)。

>>> 2+ 1
3
>>> _
3
>>> print_
3
“_” 是上一个执行的表达式的输出。

8. 字典/集合推导

与列表推导式类似,我们也可以使用字典和集合推导式,它们既简单又高效。示例如下:

testDict= {i: i *iforiinxrange(10)}
testSet= {i *2foriinxrange(10)}
print(testSet)
print(testDict)
#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

注意:两个语句的区别仅在于一个 <:> 符号。另外,在 Python3 中运行上述代码时,需将 <xrange> 替换为 <range>。

9. 调试脚本

借助 <pdb> 模块,我们可以在 Python 脚本中设置断点。示例如下:

import pdb
pdb.set_trace()

你可以在脚本的任何位置插入 <pdb.set_trace()> 以设置断点,操作十分简便。

10. 开启文件分享

Python 允许运行一个 HTTP 服务器,以便从当前根目录共享文件。启动服务器的命令如下:

# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.server

上述命令将在默认端口 8000 启动服务器。你也可以通过传递最后一个参数来指定自定义端口号。

11. 检查 Python 中的对象

我们可以通过调用 dir() 方法来检查 Python 对象。以下是一个简单的示例:

test= [1,3,5,7]
print(dir(test))
[‘__add__', ‘__class__', ‘__contains__', ‘__delattr__', ‘__delitem__', ‘__delslice__', ‘__doc__', ‘__eq__', ‘__format__', ‘__ge__', ‘__getattribute__', ‘__getitem__', ‘__getslice__', ‘__gt__', ‘__hash__', ‘__iadd__', ‘__imul__', ‘__init__', ‘__iter__', ‘__le__', ‘__len__', ‘__lt__', ‘__mul__', ‘__ne__', ‘__new__', ‘__reduce__', ‘__reduce_ex__', ‘__repr__', ‘__reversed__', ‘__rmul__', ‘__setattr__', ‘__setitem__', ‘__setslice__', ‘__sizeof__', ‘__str__', ‘__subclasshook__', ‘append', ‘count', ‘extend', ‘index', ‘insert', ‘pop', ‘remove', ‘reverse', ‘sort']

12. 简化 if 语句

我们可以使用以下方式验证多个值:

if m in [1,3,5,7]:

而不是:

if m==1 or m==3 or m==5 or m==7:

或者,对于 in 操作符,我们也可以使用 ‘{1,3,5,7}' 代替 ‘[1,3,5,7]',因为在集合中查找元素的复杂度为 O(1)。

13. 一行代码计算任何数的阶乘

Python 2.x.
result= (lambdak: reduce(int.__mul__,range(1,k+1),1))(3)
print(result)
#-> 6
Python 3.x.
import functools
result= (lambdak: functools.reduce(int.__mul__,range(1,k+1),1))(3)
print(result)
#-> 6

14. 找到列表中出现最频繁的数

test= [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test),key=test.count))
#-> 4

15. 重置递归限制

Python 默认将递归次数限制为 1000 次,我们可以通过以下方式重置该值:

import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001

请仅在必要时采用上述技巧。

16. 检查一个对象的内存使用

在 Python 2.7 中,一个 32 比特的整数占用 24 字节,而在 Python 3.5 中则占用 28 字节。为了确定内存使用情况,我们可以调用 getsizeof 方法:

在 Python 2.7 中

import sys
x=1
print(sys.getsizeof(x))
#-> 24
在 Python 3.5 中
import sys
x=1
print(sys.getsizeof(x))
#-> 28

17. 使用 __slots__ 来减少内存开支

你是否注意到你的 Python 应用占用了大量资源,特别是内存?有一个技巧是使用 __slots__ 类变量,这在一定程度上可以减少内存开支。

import sys
classFileSystem(object):
def __init__(self,files,folders,devices):
self.files= files
self.folders= folders
self.devices= devices
print(sys.getsizeof(FileSystem))
classFileSystem1(object):
__slots__= [‘files','folders','devices']
def __init__(self,files,folders,devices):
self.files= files
self.folders= folders
self.devices= devices
print(sys.getsizeof(FileSystem1))
#In Python 3.5
#1-> 1016
#2-> 888

从结果中可以明显看出确实节省了内存,但你仅应在类的内存开销不必要地大时才使用 __slots__。务必在对应用进行性能分析后再使用它,否则只会使代码变得难以维护而缺乏实际益处。

【译者注:在我的 win10 python2.7 中上面的结果是:

#In Python 2.7 win10
#1-> 896
#2-> 1016

因此,这种比较方式并不完全令人信服。使用 __slots__ 的主要目的是限定对象的属性信息;另外,当生成大量对象时,开销可能会小一些。具体细节可参见 python 官方文档:

The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because dict is not created for each instance. 】

18. 使用 lambda 来模仿输出方法

import sys
lprint=lambda *args:sys.stdout.write(” “.join(map(str,args)))
lprint(“python”,”tips”,1000,1001)
#-> python tips 1000 1001

19.从两个相关的序列构建一个字典

t1= (1,2,3)
t2= (10,20,30)
print(dict(zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}

20. 一行代码搜索字符串的多个前后缀

print(“http://www.google.com”.startswith((“http://”,”https://”)))
print(“http://www.google.co.uk”.endswith((“.com”,”.co.uk”)))
#1-> True
#2-> True

21. 不使用循环构造一个列表

import itertools
test= [[-1,-2],[30,40],[25,35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]

22. 在 Python 中实现一个真正的 switch-case 语句

以下代码使用字典来模拟构造一个 switch-case。

def xswitch(x):
returnxswitch._system_dict.get(x,None)
xswitch._system_dict= {‘files': 10,'folders': 5,'devices': 2}
print(xswitch(‘default'))
print(xswitch(‘devices'))
#1-> None
#2-> 2

总结

以上所述是小编给大家介绍的有关Python的22个编程技巧,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表