python 小技巧
好早之前写的,现在看也没啥用

缓存机制

缓存以前这个函数返回过的值,maxsize是缓存的最大空间, typed 不太用得到。

def lru_cache(maxsize=128, typed=False):
    """Least-recently-used cache decorator.

    If *maxsize* is set to None, the LRU features are disabled and the cache
    can grow without bound.

    If *typed* is True, arguments of different types will be cached separately.
    For example, f(3.0) and f(3) will be treated as distinct calls with
    distinct results.
from functools import lru_cache
import click

def fib(n: int):
    if n == 1 or n == 2:
        return 1
    return fib(n-1) + fib(n-2)

@click.command()
@click.option('--cache', default=False, is_flag=True)
@click.argument('num', type=int)
def main(cache, num):
    global fib
    if cache:
        fib = lru_cache(fib)
    click.echo(fib(num))

main()

"""
time python .\test.py --cache 40
102334155
00:00:00.1137500

time python .\test.py 40        
102334155
00:00:23.0075758
"""

从大量数据中解包出特定位置的某个

a = list(range(10))
_, item, *args = a  # print(_, item, args) -> 0 1 [2, 3, 4, 5, 6, 7, 8, 9]

统计出现次数

from collections import Counter
import random

s = [random.randrange(5) for _ in range(1000)]

c = Counter(s)
print(c) # Counter({4: 204, 1: 203, 3: 202, 2: 198, 0: 193})

双端队列

from collections import deque

q = deque(range(5))
q.append('a')
q.appendleft('b'); print(q)
q.pop(); print(q)
q.popleft(); print(q)
"""
deque(['b', 0, 1, 2, 3, 4, 'a'])
deque(['b', 0, 1, 2, 3, 4])
deque([0, 1, 2, 3, 4])
"""

dataclass 数据类

In [1]: from dataclasses import dataclass
 
In [2]: @dataclass
   ...: class Player:
   ...:     name: str
   ...:     number: int
   ...:     position: str
   ...:     age: int
   ...:     grade: str
 
In [3]: james = Player('Lebron James', 23, 'SF', 25, 'S')
In [4]: james
Out[4]: Player(name='Lebron James', number=23, position='SF', age=25, grade='S')


最后修改于 2024-10-07