本文正在参加「Python主题月」,详情查看 活动连接python
若是您让任何 Python 程序员讲述 Python 的优点,他会引用简洁和高可读性做为最有影响力的优点。在本 Python 教程中,咱们将介绍许多基本的 Python 教程和技巧,这些技巧和技巧将验证上述两点。linux
自从我开始使用 Python 以来,我一直在收集这些有用的快捷方式。还有什么事比分享咱们所知道的而且可使他人受益的东西更加有意义?git
因此今天,我带来了一些基本的 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.使用 splat 运算符解包函数参数。
20.使用字典来存储 switch。
21.计算一行中任意数字的阶乘。
22.查找列表中出现频率最高的值。
23.重置递归限制。
24.检查对象的内存使用状况。
25.使用 slots 减小内存开销。
26.Lambda 模仿打印功能。
27.从两个相关序列建立字典。
28.在线搜索字符串中的多个前缀。
29.造成一个统一的列表,不使用任何循环。
30.在 Python 中实现真正的 switch-case 语句。
总结——Python 提示和技巧github
Python 提供了一种在一行中进行赋值和交换的直观方式。请参考下面的例子。express
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
复制代码
右边的赋值为一个新的元组播种。而左边的当即将那个(未引用的)元组解包到名称 <a>
和 <b>
。编程
分配完成后,新元组将被取消引用并标记为垃圾收集。变量的交换也发生在最终。服务器
回到目录markdown
比较运算符的聚合是另外一个有时能够派上用场的技巧。app
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# False
复制代码
三元运算符是 if-else 语句的快捷方式,也称为条件运算符。
[on_true] if [expression] else [on_false]
复制代码
如下是一些示例,您可使用它们使代码紧凑简洁。
下面的语句与它的意思相同,即“若是 y 为 9,则将 10 分配给 x,不然将 20 分配给 x ”。若是须要,咱们能够扩展运算符的连接。
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]
复制代码
基本方法是使用从 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
复制代码
咱们可使用一个列表来初始化一个 no。的变量。在解压列表时,变量的数量不该超过编号。列表中的元素。
testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
复制代码
若是您想知道代码中导入的模块的绝对位置,请使用如下技巧。
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'>
复制代码
这是一个有用的功能,咱们不少人都不知道。
在 Python 控制台中,每当咱们测试表达式或调用函数时,结果都会发送到临时名称 _(下划线)。
>>> 2 + 1
3
>>> _
3
>>> print _
3
复制代码
“_”引用上次执行的表达式的输出。
就像咱们使用列表推导同样,咱们也可使用字典/集合推导。它们易于使用且一样有效。这是一个例子。
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}
复制代码
注意 -两个语句中只有 <:> 的区别。此外,要在 Python3 中运行上述代码,请将 替换为 。
咱们能够在 模块的帮助下在 Python 脚本中设置断点。请按照如下示例进行操做。
import pdb
pdb.set_trace()
复制代码
咱们能够在脚本的任何地方指定 <pdb.set_trace()> 并在那里设置断点。这是很是方便的。
Python 容许运行 HTTP 服务器,您可使用它从服务器根目录共享文件。下面是启动服务器的命令。
python -m SimpleHTTPServer
复制代码
python3 -m http.server
复制代码
以上命令将在默认端口 8000 上启动服务器。您还能够经过将自定义端口做为最后一个参数传递给上述命令来使用自定义端口。
咱们能够经过调用 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']
复制代码
要验证多个值,咱们能够经过如下方式进行。
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]' 做为 'in' 运算符,由于 'set' 能够经过 O(1) 访问每一个元素。
有时,若是当前运行的 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\n")
print("Please upgrade to 3.5.\n")
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]
复制代码
若是您想链接列表中全部可用的标记,请参见如下示例。
>>> test = ['I', 'Like', 'Python', 'automation']
复制代码
如今,让咱们从上面给出的列表中的元素建立一个字符串。
>>> print ''.join(test)
复制代码
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]。
使用枚举器,在循环中很容易找到索引。
testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value)
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
复制代码
咱们可使用如下方法来建立枚举定义。
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
复制代码
支持此功能的编程语言并很少。可是,Python 中的函数确实会返回多个值。
请参考如下示例以查看它的工做状况。
# 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
splat 运算符提供了一种解压参数列表的艺术方式。为清楚起见,请参阅如下示例。
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
复制代码
咱们能够制做一个字典存储表达式。
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
复制代码
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
复制代码
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
复制代码
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))
#-> 4
复制代码
Python 将递归限制限制为 1000。咱们能够重置它的值。
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001
复制代码
请仅在须要时应用上述技巧。
在 Python 2.7 中,32 位整数消耗 24 字节,而在 Python 3.5 中使用 28 字节。为了验证内存使用状况,咱们能够调用 方法。
import sys
x=1
print(sys.getsizeof(x))
#-> 24
复制代码
import sys
x=1
print(sys.getsizeof(x))
#-> 28
复制代码
你有没有观察到你的 Python 应用程序消耗了大量资源,尤为是内存?这是使用<__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
复制代码
显然,您能够从结果中看到内存使用量有所节省。可是当一个类的内存开销没必要要地大时,你应该使用 __slots__
。仅在分析应用程序后执行此操做。不然,您将使代码难以更改而且没有真正的好处。
import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001)
#-> python tips 1000 1001
复制代码
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}
复制代码
print("http://www.baidu.com".startswith(("http://", "https://")))
print("https://juejin.cn".endswith((".com", ".cn")))
#1-> True
#2-> True
复制代码
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]
复制代码
若是您有一个包含嵌套列表或元组做为元素的输入列表,请使用如下技巧。可是,这里的限制是它使用了 for 循环。
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]
复制代码
统一包含列表和元组的列表的另外一种更简单的方法是使用 Python 的 < more_itertools > 包。它不须要循环。只需执行 < pip install 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]
复制代码
这是使用字典来模仿 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 提示和技巧将帮助您快速有效地完成任务。您能够将它们用于您的做业和项目。
我已经写了很长一段时间的技术博客,这是个人一篇技巧教程。但愿大家会喜欢!这里汇总了个人所有原创及做品源码:
若是你真的从这篇文章中学到了一些新东西,喜欢它,收藏它并与你的小伙伴分享。🤗最后,不要忘了❤或📑支持一下哦