sintance和type
class Foo(object): pass class Bar(Foo): pass obj = Bar() # isinstance用于判断,对象是否是指定类的实例 (错误的) # isinstance用于判断,对象是否是指定类或其派生类的实例 # isinstance不精准 print(isinstance(obj,Foo),id(obj)) #True 35558624 print(isinstance(obj,Bar),id(obj)) #True 35558624 print(type(obj)==Foo) #False print(type(obj)==Bar) #True
json
import json v = {"name":"海燕","age":22} str_dic = json.dumps(v) print(json.dumps(v),type(str_dic)) #{"name": "u6d77u71d5", "age": 22}<class 'str'> print(json.dumps(v,ensure_ascii=False)) #{"name": "海燕", "age": 22}
OrderedDict
使用字典时,key是无序的。在对字典做迭代时,我们无法确定key的顺序。如果要保持key的顺序,可以用OrderedDict
from collections import OrderedDict od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) for i in od.keys(): print(i)
Counter
计数器
from collections import Counter c = Counter('abcdeabcdabcaba') print(c["a"]) #5
defaultdict
from collections import defaultdict values = [11,22,33,44,55,66,77,88,99] my_dict = defaultdict(list) for v in values: if v>66: my_dict['k1'].append(v) print(my_dict)
模拟defaultdict
values = [11,22,33,44,55,66,77,88,99] my_dict = {} for v in values: if v>66: if "k1" in my_dict.keys(): my_dict['k1'].append(v) else: my_dict["k1"]=[] my_dict['k1'].append(v) print(my_dict)
deque
是为了高效实现插入和删除操作的双向队列,适用于队列和栈
from collections import deque q = deque(['a','b','c']) q.append('ee')#添加元素 q.append('ff') q.append('qq') print(q) q.appendleft('www')#从左边添加 print(q) q.pop() #删除元素 q.popleft() #从左边删除元素 print(q)
元祖的排序
anwsers = [(1,2),(3,2),(2,2)] x = sorted(anwsers,key=lambda x:x[0],reverse=True) print(x)