選自medium,做者:Martin Heinz,機器之心編譯,參與:王子嘉、熊宇軒。python
介紹 Python 炫酷功能(例如,變量解包,偏函數,枚舉可迭代對象等)的文章層出不窮。可是還有不少 Python 的編程小技巧鮮被說起。所以,本文會試着介紹一些其它文章沒有提到的小技巧,這些小技巧也是我平時會用到的的。讓咱們一探究竟吧!正則表達式
整理用戶輸入的問題在編程過程當中極爲常見。一般狀況下,將字符轉換爲小寫或大寫就夠了,有時你可使用正則表達式模塊「Regex」完成這項工做。可是若是問題很複雜,可能有更好的方法來解決:編程
user_input = "This\nstring has\tsome whitespaces...\r\n"character_map = { ord('\n') : ' ', ord('\t') : ' ', ord('\r') : None}user_input.translate(character_map) # This string has some whitespaces... 複製代碼
在本例中,你能夠看到空格符「\ n」和「\ t」都被替換成了單個空格,「\ r」都被刪掉了。這只是個很簡單的例子,咱們能夠更進一步,使用「unicodedata」程序包生成大型重映射表,並使用其中的「combining()」進行生成和映射,咱們能夠
數組
迭代器切片(Slice)bash
import itertoolss = itertools.islice(range(50), 10, 20) # <itertools.islice object at 0x7f70fab88138>for val in s: ...複製代碼
跳過可迭代對象的開頭app
string_from_file = """// Author: ...// License: ...//// Date: ...Actual content..."""import itertoolsfor line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split("\n")): print(line)複製代碼
只包含關鍵字參數的函數 (kwargs)ide
def test(*, a, b): passtest("value for a", "value for b") # TypeError: test() takes 0 positional arguments...test(a="value", b="value 2") # Works...複製代碼
建立支持「with」語句的對象函數
class Connection: def __init__(self): ... def __enter__(self): # Initialize connection... def __exit__(self, type, value, traceback): # Close connection...with Connection() as c: # __enter__() executes ... # conn.__exit__() executes複製代碼
from contextlib import contextmanager@contextmanagerdef tag(name): print(f"<{name}>") yield print(f"</{name}>")with tag("h1"): print("This is Title.")複製代碼
用「__slots__」節省內存優化
若是你曾經編寫過一個建立了某種類的大量實例的程序,那麼你可能已經注意到,你的程序忽然須要大量的內存。那是由於 Python 使用字典來表示類實例的屬性,這使其速度很快,但內存使用效率卻不是很高。一般狀況下,這並非一個嚴重的問題。可是,若是你的程序所以受到嚴重的影響,不妨試一下「__slots__」:ui
class Person: __slots__ = ["first_name", "last_name", "phone"] def __init__(self, first_name, last_name, phone): self.first_name = first_name self.last_name = last_name self.phone = phone複製代碼
當咱們定義了「__slots__」屬性時,Python 沒有使用字典來表示屬性,而是使用小的固定大小的數組,這大大減小了每一個實例所需的內存。使用「__slots__」也有一些缺點:咱們不能聲明任何新的屬性,咱們只能使用「__slots__」上現有的屬性。並且,帶有「__slots__」的類不能使用多重繼承。
限制「CPU」和內存使用量
若是不是想優化程序對內存或 CPU 的使用率,而是想直接將其限制爲某個肯定的數字,Python 也有一個對應的庫能夠作到:
import signalimport resourceimport os# To Limit CPU timedef time_exceeded(signo, frame): print("CPU exceeded...") raise SystemExit(1)def set_max_runtime(seconds): # Install the signal handler and set a resource limit soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard)) signal.signal(signal.SIGXCPU, time_exceeded)# To limit memory usagedef set_max_memory(size): soft, hard = resource.getrlimit(resource.RLIMIT_AS) resource.setrlimit(resource.RLIMIT_AS, (size, hard))複製代碼
控制能夠/不能夠導入什麼
def foo(): passdef bar(): pass__all__ = ["bar"]複製代碼
實現比較運算符的簡單方法
from functools import total_ordering@total_orderingclass Number: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): return self.value == other.valueprint(Number(20) > Number(3))print(Number(1) < Number(5))print(Number(15) >= Number(15))print(Number(10) <= Number(2))複製代碼
結語