如果你问一个Python程序员,Python有什么优点,他肯定会说Python的简洁性和高可读性。本文将介绍许多基本的Python技巧和窍门来验证以上两点。
所有这些技巧可以帮助您减小代码量并优化执行效率。此外,你可以在常规的项目中灵活使用他们。
每一个技巧都有例子和一个简短的解释。您可以执行和测试这些例子。
以下是目录:
1、交换两个变量的值。
2、比较运算符链
3、三元算子在条件赋值中的应用
4、多行字符串
5、存储列表元素到新变量中。
6、打印导入模块的文件路径
7、使用“_”运算符。
8、字典/集合
9、调试脚本
10、文件共享
11、Python对象检查
12、简化if语句
13、运行时检测Python版本
14、合并多个字符串
15、四种方法反转 string/list.
16、玩转枚举
17、使用Python枚举
18、函数返回多个值
19、函数参数提取
20、用字典存储开关
21、一行语句计算阶乘
22、列表中找出出现频率最高的元素
23、重置回归限制
24、查看一个对象的内存占用
25、使用__slots__减少内存开销
26、Lambda表达式模仿print函数
27、通过两个相关序列创建字典
28、在字符串中搜索前缀
29、不用循环生成一个归一化列表
30、实现一个真正的switch-case语句
在这里还是要推荐下我自己建的Python开发学习群:483546416,群里都是学Python开发的,如果你正在学习Python ,小编欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2018最新的Python进阶资料和高级开发教程,欢迎进阶中和进想深入Python的小伙伴
1、交换两个变量的值。
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
2、连续比较运算符
连续比较运算符是另一个有时很有用的技巧。
n =10
result =1< n <20
print(result)
# True
result =1> n <=9
print(result)
# False
3、三元运算符在条件赋值中的应用
三元运算符是IF语句的快捷方式,也称为条件运算符。
[on_true] if [expression] else [on_false]
以下几个例子可以让你的代码简洁明了。
x = 10 if (y == 9) else 20
同样,我们也可以用类对象做同样的事情。
x = (classA if y == 1 else classB)(param1, param2)
以上例子中classA或classB的构造函数会被调用
以下函数可以计算最小值
def small(a, b, c):
return a if a <= b and a <= c else (b if b <= a and b <= c else c)
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、多行字符串
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控制台中,每当我们测试表达式或调用函数时,结果都会发送到临时名称,即(_)。
>>> 2 + 1
3
>>> _
3
>>> print _
3
8、字典/集合内嵌初始化
testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(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}
9、调试脚本
我们可以在<Pb>模块的帮助下在Python脚本中设置断点。请参照下面的例子。
import pdb
pdb.set_trace()
10、设置文件共享
Python允许运行HTTP服务器,您可以使用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:
我们也可以用‘{1,3,5,7}’替代‘[1,3,5,7]’,因为集合访问元素的时间复杂度是O(1)
13、运行时检测Python版本
有时,如果当前运行的Python引擎小于支持的版本,我们可能不想执行某些程序。为了实现这一点,可以使用下面的编码片段。
import sys
#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5 ")
print("Please upgrade to 3.5. ")
sys.exit(1)
#Print Python version in a readable format.
print("Current Python version: ", sys.version)
我们同样可以使用sys.version_info >= (3, 5)来替换sys.hexversion!= 50660080
运行Python 2.7时的输出为如下内容:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
Sorry, you aren't running on Python 3.5
Please upgrade to 3.5.
运行Python 3.5时的输出为如下内容:
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05)
[GCC 5.3.0]
14、合并多个字符串
如果你想把列表中的字符串全都链接起来可以用如下语句:
>>> test = ['I', 'Like', 'Python', 'automation']
>>> print ''.join(test)
15、四种方法反转 string/list.
# 通过列表自身反转
testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]
# 在循环中反转
for element in reversed([1,3,5]): print(element)
#1-> 5
#2-> 3
#3-> 1
# 在同一行中反转标量
"Test Python"[::-1]
以上表达式会返回 ”nohtyP tseT”
# 通过切片反转
[1, 3, 5][::-1]
以上表达式会返回 [5, 3, 1].
16、玩转迭代器
通过迭代器可以在循环中轻松使用索引
testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value)
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
17、使用Python枚举
我们可以通过如下方法定义枚举
class Shapes:
Circle, Square, Triangle, Quadrangle = range(4)
print(Shapes.Circle)
print(Shapes.Square)
print(Shapes.Triangle)
print(Shapes.Quadrangle)
#1-> 0
#2-> 1
#3-> 2
#4-> 3
18、函数返回多个值
# function returning multiple values.
def x():
return 1, 2, 3, 4
# Calling the above function.
a, b, c, d = x()
print(a, b, c, d)
#-> 1 2 3 4
19、函数参数提取
def test(x, y, z):
print(x, y, z)
testDict = {'x': 1, 'y': 2, 'z': 3}
testList = [10, 20, 30]
test(*testDict)
test(**testDict)
test(*testList)
#1-> x y z
#2-> 1 2 3
#3-> 10 20 30
20、用字典存储开关
stdcalc = {
'sum': lambda x, y: x + y,
'subtract': lambda x, y: x - y
}
print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3))
#1-> 12
#2-> 6
21、一行语句计算阶乘
Python 2.x.
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
Python 3.x.
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
22、列表中找出出现频率最高的元素
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))
#-> 4
23、重置回归限制
设置回归次数上限
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001
24、查看一个对象的内存占用
In Python 2.7.
import sys
x=1
print(sys.getsizeof(x))
#-> 24
In Python 3.5.
import sys
x=1
print(sys.getsizeof(x))
#-> 28
25、使用__slots__减少内存开销
import sys
class FileSystem(object):
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices
print(sys.getsizeof( FileSystem ))
class FileSystem1(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
26、Lambda表达式模仿print函数
import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001)
#-> python tips 1000 1001
27、通过两个相关序列创建字典
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}
28、在字符串中搜索前缀
print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
#1-> True
#2-> True
29、不用循环将列表降维
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]
如果列表中包含子列表或元组,可以用如下代码
def unifylist(l_input, l_target):
for it in l_input:
if isinstance(it, list):
unifylist(it, l_target)
elif isinstance(it, tuple):
unifylist(list(it), l_target)
else:
l_target.append(it)
return l_target
test = [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]]
print(unifylist(test,[]))
#Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
另一个方法是使用more_itertools包
import more_itertools
test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]
print(list(more_itertools.collapse(test)))
#Output=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
30、实现一个真正的switch-case语句
def xswitch(x):
return xswitch._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技巧和窍门可以帮助你快速高效地完成工作。你可以用它们来完成你的任务和项目。