1、格式化字符串f-string
user = "Mike" log_message = f‘User{user} has logged in‘
2、路径管理库Pathlib
3、类型提示Type hinting
def sentence_has_animal(sentence:str) -> bool: return "animal" in sentence
4、枚举类enum
from enum import Enum, auto, unique @unique #装饰器去重复 class monster(Enum): zombie = auto() warrior = auto() bear = auto()
5、itertools模块
无限迭代器代码如下:
1 2 3 4 |
|
处理输入序列迭代器代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
组合生成器代码如下:
1 2 3 4 5 6 7 8 9 |
|
6、LRU缓存,memoization技术
from functools import lru_cache @lru_cache(maxsize=512) def fib_memoization(number:int) -> int: if number ==0 : return 0 if number ==1 : return 1 return fib_memoization(number - 1) start = time.time() fib_memoization(40) print(f‘Duration:{time.time() - start}s‘)
7、可扩展的可迭代对象解包
head, *bodey, tail = range(5) # 0, [1,2,3], 4
8、Data class装饰器,用来减少对样板代码的使用,该装饰器会自动生成__init()__和__repr()__方法。
class Armor: def __init__(self, armor:float, description:str, level:int = 1): self.armor = armor self.level = level self.description = description def power(self) -> float: return self.armor * self.level armor = Armor(5.2, "common armor.", 2) armor.power() #10.4 ###使用Data Class实现相同的Armor类 from dataclasses import dataclass @dataclass class Armor: armor : float description : str level : int = 1 def power(self) -> float: return self.armor *self.level armor = Armor(5.2, "common armor.", 2) armor.power()
9、bisect模块保持列表排序:
这是一个免费的二分查找实现和快速插入有序序列的工具。也就是说,你可以使用:
import bisect bisect.insort(list, element)
原文地址:https://www.cnblogs.com/hotsnow/p/10940685.html