python中内置函数和json、pickle的数据序列化代码实例
程序员文章站
2024-01-05 20:13:34
内置函数
map
res = map(lambda n:n**n, range(10))
res1 = [lambda i:i*2 for i in range(10)]...
内置函数
map
res = map(lambda n:n**n, range(10)) res1 = [lambda i:i*2 for i in range(10)] for i in res1: print(i)
reduce
import functools res = functools.reduce(lambda x, y:x+y, range(10)) print(res)
对字典排序的函数
#对字典排序 a = {6:2, 3:12, 99:11, -1:2} print(sorted(a.items())) #指定排序方式 print(sorted(a.items(), key = lambda x:x[1]))
将两个数组拼成一个数组
a = [1,2,3,4] b = ['a', 'b', 'c', 'd'] for i in zip(a,b): print(i)
json和pickle数据序列化
# info = { # 'name':'dancheng', # 'age':20 # } # f = open('test.text', 'w') # f.write(str(info)) #将json对象变成字符串 # f.close() # f = open('test.text','r') # data = eval(f.read()) #将字符串转成json对象 # f.close() # print(data['name'])
调用json包
info = { 'name':'dancheng1', 'age':20, 'func':sayhi('dancheng') } f = open('test.text', 'w') f.write(json.dumps({1:2})) f.close()
调用pickle包
import pickle info = { 'name':'dancheng1', 'age':20, } f = open('test.text', 'wb') f.write(pickle.dumps(info)) f.close() import pickle f = open('test.text', 'rb') data = pickle.loads(f.read()) f.close() print(data)