选自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))复制代码
结语