i = 13000000 a = 99.056 s = '中国人民123abc' lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] tu = (-5, 10, 8) coll = {4, 5, 6} dic = {'a':'apple', 'b':'banana', 'g':'grape', 'o':'orange'} data = [i, a, s, lst, tu, coll, dic]
with open('sample_pickle.dat', 'wb') as f: try: pickle.dump(len(data), f) #表示后面将要写入的数据个数 for item in data: pickle.dump(item, f) except: print('写文件异常!') #如果写文件异常则跳到此处执行
with open('sample_pickle.dat', 'rb') as f: n = pickle.load(f) #读出文件的数据个数 for i in range(n): x = pickle.load(f) print(x)
n = 1300000000 x = 96.45 b = True s = 'a1@中国' sn = struct.pack('if?', n, x, b) # 序列化 length = len(sn) # 序列化后的长度,第14行会用到 with open('sample_struct.dat', 'wb') as fp: fp.write(sn) # 写入字节串 fp.write(s.encode()) # 字符串直接编码为字节串写入
with open('sample_struct.dat', 'rb') as fp: sn = fp.read(length) # 读length个字节 tu = struct.unpack('if?', sn) print(tu) n, x, bl = tu print('n=', n) print('x=', x) print('bl=', bl) s = fp.read(9).decode() print('s=', s)
demo(*(3,), **{'a': 1, 'b': 2}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: demo() got multiple values for argument 'a'
demo(*(3,), **{'c':1, 'b':2}) # ok
变量作用域
局部变量
在某个作用域内任意位置只要有为变量赋值的操作,该变量在这个作用域内就是局部变量,除非使用 global 进行了声明。
1 2 3 4 5 6 7 8 9 10 11 12
x = 3
deff(): print(x) x = 5 print(x)
f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f UnboundLocalError: local variable 'x' referenced before assignment
a = Test() b = Test() c = a @ b # __matmul__ <__main__.Test object at 0x000001E098F8A2E0> d = 1 @ a # __rmatmul__ 1 e = a @ 2# __matmul__ 2 c @= c # __imatmul__ <__main__.Test object at 0x000001E098F2A550> d @= 3# __imatmul__ 3
import numpy as np x = np.ones(3) y = np.eye(3) * 3 y[0, 2] = 5 y[2, 0] = 3 print(x @ y) # [6. 3. 8.]
template <classT> structSelector { // MUST return const int&, not int. // if return int, segmentation fault will occur. // I have spent much time because of this. constint& operator()(const T& obj)const{ return obj.first; } };
intmain(){ // _Rb_tree: red-black tree in STL. using tree_type = _Rb_tree<int, Node, Selector<Node>, less<int>>; using iterator_type = tree_type::iterator; using result_pair_type = pair<tree_type::iterator, bool>; tree_type tree;