直接交換2個(gè)數(shù)字的位置
Python 提供了一種直觀的方式在一行代碼中賦值和交換(變量值)。如下所示:
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
在上面代碼中,賦值的右側(cè)形成了一個(gè)新元組,而左側(cè)則立刻將該(未被引用的)元組解包到名稱和 。
待賦值完成后,新元組就變成了未被引用狀態(tài),并且被標(biāo)為可被垃圾回收,最終也就發(fā)生了數(shù)字交換。
鏈接比較操作符
比較運(yùn)算符的聚合是另一種有時(shí)用起來很順手的技巧。
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# False
使用三元操作符進(jìn)行條件賦值
三元操作符是 if-else 語句(也就是條件操作符)的快捷操作:
[on_true] if [expression] else [on_false]
下面舉兩個(gè)例子例子,展示一下可以用這種技巧讓你的代碼更緊湊更簡(jiǎn)潔。
下面的語句意思是“如果 y 為 9,就向 x 賦值 10,否則向 x 賦值 20”。如果需要,我們可以擴(kuò)展這個(gè)操作符鏈接:
x = 10 if (y == 9) else 20
同樣,我們對(duì)類對(duì)象也可以這樣操作:
x = (classA if y == 1 else classB)(param1, param2)
在上面這個(gè)例子中,classA 與 classB 是兩個(gè)類,其中一個(gè)類構(gòu)造函數(shù)會(huì)被調(diào)用。
使用多行字符串
這個(gè)方法就是使用源自 C 語言的反斜杠:
multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr)
# select * from multi_row where row_id < 5
另一個(gè)技巧就是用三引號(hào):
multiStr = """select * from multi_row
where row_id < 5"""
print(multiStr)
#select * from multi_row
#where row_id < 5
上述方法的一個(gè)常見問題就是缺少合適的縮進(jìn),如果我們想縮進(jìn),就會(huì)在字符串中插入空格。
所以最終的解決方案就是將字符串分成多行,并將整個(gè)字符串包含在括號(hào)中:
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
將一個(gè)列表的元素保存到新變量中
我們可以用一個(gè)列表來初始化多個(gè)變量,在解析列表時(shí),變量的數(shù)量不應(yīng)超過列表中的元素?cái)?shù)量,否則會(huì)報(bào)錯(cuò)。
testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
打印出導(dǎo)入的模塊的文件路徑
如果你想知道代碼中導(dǎo)入的模塊的絕對(duì)路徑,用下面這條技巧就行了:
import threading
import socket
print(threading)
print(socket)
#1-
#2-
使用交互式“_”操作符
其實(shí)這是個(gè)相當(dāng)有用的功能,只是我們很多人并沒有注意到。
在 Python 控制臺(tái)中,每當(dāng)我們測(cè)試一個(gè)表達(dá)式或調(diào)用一個(gè)函數(shù)時(shí),結(jié)果都會(huì)分配一個(gè)臨時(shí)名稱,_(一條下劃線)。
>>> 2 + 1
3
>>> _
3
>>> print _
3
這里的“_”是上一個(gè)執(zhí)行的表達(dá)式的結(jié)果。
字典/集合推導(dǎo)
就像我們使用列表表達(dá)式一樣,我們也可以使用字典/集合推導(dǎo)。非常簡(jiǎn)單易用,也很有效,示例如下:
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}
注意:在這兩個(gè)語句中,<:>只有一處差異。另外,如果想用 Python3 運(yùn)行以上代碼,要把
替換為
。
調(diào)試腳本
我們可以借助
模塊在 Python 腳本中設(shè)置斷點(diǎn),如下所示:
import pdb
pdb.set_trace()
我們可以在腳本的任意位置指定
設(shè)置文件分享
Python 能讓我們運(yùn)行 HTTP 服務(wù)器,可以用于分享服務(wù)器根目錄中的文件。啟動(dòng)服務(wù)器的命令如下:
# Python 2:
python -m SimpleHTTPServer
# Python 3:
python3 -m http.server
上述命令會(huì)在默認(rèn)端口 8000 啟動(dòng)一個(gè)服務(wù)器,你也可以使用自定義端口,將端口作為最后元素傳入上述命令中即可。
在Python中檢查對(duì)象
我們可以通過調(diào)用 dir() 方法在 Python 中檢查對(duì)象,下面是一個(gè)簡(jiǎn)單的例子:
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']
簡(jiǎn)化if語句
我們可以通過如下方式來驗(yàn)證多個(gè)值:
if m in [1,3,5,7]:
而不用這樣:
if m==1 or m==3 or m==5 or m==7:
對(duì)于in操作符,我們也可以用‘{1,3,5,7}’而不是‘[1,3,5,7]’,因?yàn)椤畇et’可以通過O(1)獲取每個(gè)元素。
在運(yùn)行時(shí)檢測(cè)Python的版本
有時(shí)如果當(dāng)前運(yùn)行的 Python 低于支持版本時(shí),我們可能不想執(zhí)行程序。那么就可以用下面的代碼腳本檢測(cè) Python 的版本。還能以可讀格式打印出當(dāng)前所用的 Python 版本。
import sys
#檢測(cè)當(dāng)前所用的Python版本
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)
#以可讀格式打印出Python版本
print("Current Python version: ", sys.version)
另外,你可以將上面代碼中的 sys.hexversion!= 50660080 替換為 sys.version_info >= (3, 5)。
在 Python 2.7 中運(yùn)行輸出為:
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中運(yùn)行輸出為:
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]
組合多個(gè)字符串
如果你想拼接列表中的所有 token,那么看看下面的例子就明白了:
>>> test = ['I', 'Like', 'Python', 'automation']
現(xiàn)在我們從上面列表的元素中創(chuàng)建一個(gè)字符串:
>>> print ''.join(test)
翻轉(zhuǎn)字符串/列表的4種方式
#翻轉(zhuǎn)列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]
#在循環(huán)中迭代時(shí)翻轉(zhuǎn)
for element in reversed([1,3,5]): print(element)
#1-> 5
#2-> 3
#3-> 1
#翻轉(zhuǎn)一行代碼中的字符串
"Test Python"[::-1]
我們會(huì)得到結(jié)果“nohtyP tseT”。
#用切片翻轉(zhuǎn)一個(gè)列表
[1, 3, 5][::-1]
上面的命令會(huì)得到輸出結(jié)果 [5, 3, 1]。
使用枚舉
使用枚舉可以很容易地在循環(huán)中找到索引:
testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value)
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
在 Python 中使用枚舉量
我們可以用如下方法來創(chuàng)建枚舉定義:
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
從函數(shù)中返回多個(gè)值
支持這種功能的編程語言并不多,然而,Python 中的函數(shù)可以返回多個(gè)值。
可以參考下面的例子看看是怎么做到的:
# 返回多個(gè)值的函數(shù)
def x():
return 1, 2, 3, 4
# 調(diào)用上面的函數(shù)
a, b, c, d = x()
print(a, b, c, d)
#-> 1 2 3 4
使用*運(yùn)算符解壓縮函數(shù)參數(shù)
運(yùn)算符提供了一種很藝術(shù)的方式來解壓縮參數(shù)列表,參看如下示例:
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
使用字典來存儲(chǔ)表達(dá)式
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
一行代碼計(jì)算任何數(shù)字的階乘
# 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
找到一個(gè)列表中的出現(xiàn)最頻繁的值
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))
#-> 4
重置遞歸限制
Python 將遞歸限制到 1000,我們可以重置這個(gè)值:
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001
提示:在有必要時(shí)才使用該技巧。
檢查一個(gè)對(duì)象的內(nèi)存使用
在 Python 2.7 中,一個(gè) 32-bit 的整數(shù)值會(huì)占用 24 字節(jié),而在 Python 3.5 中會(huì)占用 28 字節(jié)。我們可以調(diào)用 方法來驗(yàn)證內(nèi)存使用。
在 Python 2.7 中:
import sys
x=1
print(sys.getsizeof(x))
#-> 24
在 Python 3.5 中:
import sys
x=1
print(sys.getsizeof(x))
#-> 28
使用_slots_減少內(nèi)存消耗
不知道你是否注意過你的 Python 程序會(huì)占用很多資源,特別是內(nèi)存?這里分享給你一個(gè)技巧,使用 < slots > 類變量來減少程序的內(nèi)存消耗。
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
很明顯,從解雇中可以看到節(jié)省了一些內(nèi)存。但是應(yīng)當(dāng)在一個(gè)類的內(nèi)存占用大得沒有必要時(shí)再使用這種方法。對(duì)應(yīng)用進(jìn)行性能分析后再使用它,不然除了會(huì)讓代碼難以改動(dòng)外沒有什么好處。
使用拉姆達(dá)來模仿輸出方法
import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001)
#-> python tips 1000 1001
從兩個(gè)相關(guān)序列中創(chuàng)建一個(gè)字典
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}
用一行代碼搜索字符串的前后綴
print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
#1-> True
#2-> True
不使用任何循環(huán),構(gòu)造一個(gè)列表
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]
如果輸入列表中有嵌入的列表或元組作為元素,那么就使用下面這種方法,不過也有個(gè)局限,它使用了 for 循環(huán):
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中實(shí)現(xiàn)一個(gè)真正的switch-case語句
下面是使用字典模仿一個(gè) switch-case 構(gòu)造的代碼示例:
在學(xué)習(xí)過程中有什么不懂得可以加我的
python學(xué)習(xí)交流扣扣qun,784758214
群里有不錯(cuò)的學(xué)習(xí)視頻教程、開發(fā)工具與電子書籍。
與你分享python企業(yè)當(dāng)下人才需求及怎么從零基礎(chǔ)學(xué)習(xí)好python,和學(xué)習(xí)什么內(nèi)容
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
結(jié)語
希望上面列出的這些 Python 技巧和建議能幫你快速和高效地完成 Python 開發(fā),可以在項(xiàng)目中應(yīng)用它們。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
