- NumPy: Remove all rows in a NumPy array that contain non-numeric values
import numpy as np
x = np.array([[1,2,3], [4,5,np.nan], [7,8,9], [True, False, True]])
print("Original array:")
print(x)
print("Remove all non-numeric elements of the said array")
print(x[~np.isnan(x).any(axis=1)])
2 数据结构与算法 📃
- 为元组中的每个元素命名
from collections import namedtuple
Student = namedtuple('Student', "name age sex email")
s = Student('lk', 24, 'male', '1111111@qq.com')
s.name
s.age
- 字典根据values排序
sorted(d.items(), key=lambda x: x[1], reverse=True)
- 统计元素频率
方法1
import heapq
heapq.nlargest
方法2
from collections import Counter
c = Counter('abcdeabcdabcaba') # count elements from a string
c.most_common(3) # three most common elements
- 多个字典的公共键
dall = [{'a': 1, 'c': 3, 'b': 2}, {'a': 2, 'd': 3}, {'a': 0}]
reduce(lambda a, b: a & b, map(dict.keys, dall))
- 最多n条历史记录
from collections import deque
dq=deque((),9)
3 字符串相关 🔤
- 拆分含有多种分隔符的字符串
re.split('[-_;,=]+', s)
- 调整字符串文本格式
dt='2021-05-01'
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', dt)
- 字符串左、右、居中对齐
str.ljust
str.center
str.rjust
format(s, '<10')
format(s, '^10')
4 对象迭代与反迭代 👍
- 生成器实现可迭代对象(__iter__函数中使用_yield_)
# 使用yield实现迭代器,不需要实现迭代器类
class printNum(Iterable):
def __init__(self,a,b):
self.a = a
self.b =b
def __iter__(self):
for k in range(self.a, self.b+1):
if self.is_prime(k):
yield k
def is_prime(self,k):
return False if k<2 else all(map(lambda x: k%x, range(2, k)))
pn = printNum(1,30)
for n in pn:
print(n)
-
反向迭代(实现__reversed__函数)
-
迭代器切片
from itertools import islice
- 迭代多个可迭代对象
-
并行 (使用zip)
-
串行 (
from itertools import chain
)
5 文件io 📃
-
处理二进制文件
-
文件缓冲
-
临时文件
from tempfile import TemporaryFile, NamedTemporaryFile
6 数据解析及构建 🔢
- 读写csv文件
import csv
- 读写json文件
import json
- 读写xml
from xml.etree.ElementTree import ElementTree, Element,SubElement
root = ElementTree.parse('abc.xml')
7 类与对象 🐘
-
list('abc')
等价于l=list.__new__(list,'abc') list.__init(l,'abc')
-
为创建大量实例减少内存
动态添加属性 a.x=value <=>a.__dict__[‘x’]=value
使用 __slots__ 声明属性,这样就不能动态添加属性
- 让对象支持上下文管理 with
需要实现类的以下方法:
__enter__
__exit__
- 创建可管理的对象属性
get_attribute,set_attribute 使用起来比较啰嗦
可使用property,fget、fset对应获取和设置属性的方法或者property装饰器
- 让类支持比较操作
from functools import total_ordering
使用total_ordering只需重载__eq__
__lt__
方法
- 对实例属性做类型检查
eg:
- 环状数据结构中内存管理
import weakref
,使用 weakref.ref 引用单向
- 根据实例方法名的字符串调用方法
getattr
from operator import methodcaller
8 多线程并发 🔜
- 线程间通信
from queue import Queue
线程安全
-
线程间事件通知
-
线程本地数据
web 视频服务器例子(待写)
9 装饰器 🖼
- 为函数增加缓存
from functools import wraps
def memo(func):
cache = {}
@warps(func)
def wrap(*args, **kwargs):
res = cache.get(args)
if not res:
cache[args] = func(*args, **kwargs)
return res
return wrap
- 带参数的装饰器(函数参数检查例子)
from functools import wraps
import inspect
def type_assert(*ty_args, **ty_kwargs):
def decorator(func):
func_sig = inspect.signature(func)
bind_type = func_sig.bind_partial(*ty_args, **ty_kwargs).arguments
@wraps(func)
def wrap(*args, **kwargs):
for name, obj in func_sig.bind(*args, **kwargs).arguments.items():
type_ = bind_type.get(name)
if type_:
if not isinstance(obj, type_):
raise TypeError('%s must be %s' % (name,type_))
return func(*args, **kwargs)
return wrap
return decorator
- 类中定义装饰器
便于修改属性和拓展功能
例子 实现了以下功能:
- 把每次函数调用时间,执行时间,调用次数写入日志。
- 可以对被装饰函数分组,调用信息可以记录到不同的日志。
- 动态修改参数,如日志格式。
- 动态打开关闭日志。
import time
import logging
DEFAULT_FORMAT = '%(func_name)s -> %(call_time)s\t%(used_time)s\t%(call_n)s'
class CallInfo:
def __init__(self, log_path, format=DEFAULT_FORMAT, on_off=True):
self.log = logging.getLogger(log_path)
self.log.addHandler(logging.FileHandler(log_path))
self.log.setLevel(logging.INFO)
self.format = format_
self.is_on = on_off
#装饰器方法
def info(self, func):
_call_n = 0
def warp(*args, **kwargs):
func_name = func.__name__
call_time = time.strftime("%x %X", time.localtime())
t0 = time.time()
res = func(*args, **kwargs)
used_time = time.time() = t0
nonlocal _call_n
_call_n += 1
call_n = _call_n
if self.is_on:
self.log.info(self.format % locals())
return res
return wrap
def set_format(self, format_):
self.format = format_
def turn_on_off(self, on_off):
self.on_off = on_off
#使用方法:
ci1 = CallInfo('mylog0.log')
ci2 = CallInfo('mylog1.log')
@ci1.info
def f():
pass
f()
ci1.set_format('%(func_name)s -> %(call_time)s\t%(used_time)s')
f()
@ci2.info
def g():
pass
- 函数运行超时装饰器
import errno
import signal
import functools
import os
def timeout(seconds=10, error_message=os.strerror(errno.ETIMEDOUT)):
def decorator(func):
def _handle_timeout(signum, frame):
raise Exception(error_message)
@functools.wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator
# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
...
# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
time.sleep(34)
# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
...