Python3的書寫技巧和應用

地道的循環

for i, name in enumerate(names):
    print(i, name)

直接交換2個數字的位置

x, y = y, x
print(x, y)

鏈接比較操作符

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

result = 11 > n < 20
print(result)
>>> True

使用三元操作符進行條件賦值

#三元操作符是 if-else 語句(也就是條件操作符)的快捷操作
#[on_true] if [expression] else [on_false]
x = 10 if (y == 9) else 20


#同樣,我們對類對象也可以這樣操作:
x = (classA if y == 1 else classB)(param1, param2)

將一個列表的元素保存到新變量中

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

打印出導入的模塊的文件路徑

import threading 
import socket
print(threading)
print(socket)
>>> <module 'threading' from '/usr/lib/python3.7/threading.py'>
>>> <module 'socket' from '/usr/lib/python3.7/socket.py'>

使用交互式“_”操作符

#在 Python3 控制檯中,每當我們測試一個表達式或調用一個函數時,結果都會分配一個臨時名稱,_(一條下劃線)
#這裏的"_"是上一個執行的表達式的結果。
>>> 2 + 1
3
>>> _
3
>>> print(_)
3

字典/集合推導

testDict = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(10)}
print(testDict)
print(testSet)

>>> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

調試腳本

#<pdb> 模塊在 Python3 腳本中設置斷點
import pdb
pdb.set_trace()

設置文件分享

#啓用http服務器並設置端口爲8000
$ python -m http.server 8000

在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']

簡化if語句

#驗證多個值
if m in [1,3,5,7]:

#也可以用字符串
if m in '{1,3,5,7}'

在運行時檢測Python的版本

import sys
if not sys.version_info >= (3,5):
    print("Sorry, you aren't running on Python 3.5 or late\n")
    print("Please upgrade to 3.5 or late.\n")
    sys.exit(1)

組合多個字符串

test = ['I', 'Like', 'Python', 'automation']
print(" ".join(test))

翻轉字符串/列表的4種方式

testList = [1, 3, 5]
testList.reverse()
print(testList)
>>> [5, 3, 1]

#在循環中迭代時翻轉
for element in reversed([1,3,5]): print(element)
>>> 5
>>> 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)
>>> 0 : 10
>>> 1 : 20
>>> 2 : 30

#在 Python3 中使用枚舉量
#我們可以用如下方法來創建枚舉定義
class Shapes:
    Circle, Square, Triangle, Quadrangle = range(4)
print(Shapes.Circle)
>>> 0
print(Shapes.Square)
>>> 1
print(Shapes.Triangle)
>>> 2
print(Shapes.Quadrangle)
>>> 3

從函數中返回多個值

返回多個值的函數
def x():
    return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
>>> 1 2 3 4

使用*運算符解壓縮函數參數

def test(x, y, z):
    print(x, y, z)
testDict = {'x': 1, 'y': 2, 'z': 3}
testList = [10, 20, 30]
test(*testDict)
>>> x y z
test(**testDict)
>>> 1 2 3
test(*testList)
>>> 10 20 30

使用字典來存儲表達式

stdcalc = {
 'sum': lambda x, y: x + y,
 'subtract': lambda x, y: x - y
}
print(stdcalc['sum'](9,3))
>>> 12
print(stdcalc['subtract'](9,3))
>>> 6

一行代碼計算任何數字的階乘

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
>>> 6

找到一個列表中的出現最頻繁的值

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

重置遞歸限制

#Python3 將遞歸限制到 1000,我們可以重置這個值
import sys
x=1001
print(sys.getrecursionlimit())
>>> 1000
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
>>> 1001

檢查一個對象的內存使用

import sys
x=1
print(sys.getsizeof(x))
>>> 14

使用 <slots> 減少內存消耗

import sys
class FileSystem1(object):
    def __init__(self, files, folders, devices):
        self.files = files
        self.folders = folders
        self.devices = devices
print(sys.getsizeof(FileSystem1))
>>> 536

class FileSystem2(object):
    __slots__ = ['files', 'folders', 'devices']
    def __init__(self, files, folders, devices):
        self.files = files
        self.folders = folders
        self.devices = devices
print(sys.getsizeof(FileSystem2))
>>> 448

使用lambda來模仿輸出方法

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.google.com".startswith(("http://", "https://")))
>>> True
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
>>> 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,[]))
>>> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]

在Python3中實現一個真正的switch-case語句

def xswitch(x): 
    return switch.system_dict.get(x, None) 
xswitch.system_dict = {'files': 10, 'folders': 5, 'devices': 2}
print(xswitch('default'))
>>> None
print(xswitch('devices'))
>>> 2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章