JSON模組
JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。它是基於ECMAScript的一個子集。 JSON採用完全獨立於語言的文字格式,但也使用了類似C語言家族的習慣(包括C、C++、Java、JavaScript、Perl、Python等)。這些特性使JSON成為理想的資料交換語言。易於人閱讀和編寫,同時也易於機器解析和生成(一般用於提升網路傳輸速率)。
JSON在python中分別由list和dict組成。
一、python類型資料和JSON資料格式互相轉換
一、python類型資料與JSON資料格式互相轉換
一、python型別資料與JSON資料格式互相轉換
一、python型別資料與JSON資料格式互相轉換pthon 中str型別至JSON轉為unicodecode型,None轉為null,dict對應為
二、資料型別,None轉為null,dict對應類型資料編解碼
#coding:utf-8 import json # 简单编码=========================================== print json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) # ["foo", {"bar": ["baz", null, 1.0, 2]}] #字典排序 print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) # {"a": 0, "b": 0, "c": 0} #自定义分隔符 print json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=(',',':')) # [1,2,3,{"4":5,"6":7}] print json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=('/','-')) # [1/2/3/{"4"-5/"6"-7}] #增加缩进,增强可读性,但缩进空格会使数据变大 print json.dumps({'4': 5, '6': 7}, sort_keys=True,indent=2, separators=(',', ': ')) # { # "4": 5, # "6": 7 # } # 另一个比较有用的dumps参数是skipkeys,默认为False。 # dumps方法存储dict对象时,key必须是str类型,如果出现了其他类型的话,那么会产生TypeError异常,如果开启该参数,设为True的话,会忽略这个key。 data = {'a':1,(1,2):123} print json.dumps(data,skipkeys=True) #{"a": 1}dump: 將物件序列化並儲存到檔案
#將物件序列化並儲存到檔案obj = ['foo', {'bar': ('baz', None , 1.0, 2)}]
json.dump(obj,f)
loads: 㜀將序列化字串序列化將序列化字串化loads: 㜀
import json obj = ['foo', {'bar': ('baz', None, 1.0, 2)}] a= json.dumps(obj) print json.loads(a) # [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]load: 將序列化字串從檔案讀取並反序列化with open(r"c:json.txt","r") as f: print json.load(f)
三、自訂複雜資料型別編解碼
例如我們碰到物件datetime,或是自訂的類別物件等json預設不支援的資料型別時,我們就需要自訂編解碼函數。有兩種方法來實作自訂編解碼。
1、方法一:自訂編解碼函數
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import datetime,json dt = datetime.datetime.now() def time2str(obj): #python to json if isinstance(obj, datetime.datetime): json_str = {"datetime":obj.strftime("%Y-%m-%d %X")} return json_str return obj def str2time(json_obj): #json to python if "datetime" in json_obj: date_str,time_str = json_obj["datetime"].split(' ') date = [int(x) for x in date_str.split('-')] time = [int(x) for x in time_str.split(':')] dt = datetime.datetime(date[0],date[1], date[2], time[0],time[1], time[2]) return dt return json_obj a = json.dumps(dt,default=time2str) print a # {"datetime": "2016-10-27 17:38:31"} print json.loads(a,object_hook=str2time) # 2016-10-27 17:38:31
2、方法二:繼承JSONEncoder和JSONDecoder類,重寫相關方法
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import datetime,json dt = datetime.datetime.now() dd = [dt,[1,2,3]] class MyEncoder(json.JSONEncoder): def default(self,obj): #python to json if isinstance(obj, datetime.datetime): json_str = {"datetime":obj.strftime("%Y-%m-%d %X")} return json_str return obj class MyDecoder(json.JSONDecoder): def __init__(self): json.JSONDecoder.__init__(self, object_hook=self.str2time) def str2time(self,json_obj): #json to python if "datetime" in json_obj: date_str,time_str = json_obj["datetime"].split(' ') date = [int(x) for x in date_str.split('-')] time = [int(x) for x in time_str.split(':')] dt = datetime.datetime(date[0],date[1], date[2], time[0],time[1], time[2]) return dt return json_obj # a = json.dumps(dt,default=time2str) a =MyEncoder().encode(dd) print a # [{"datetime": "2016-10-27 18:14:54"}, [1, 2, 3]] print MyDecoder().decode(a) # [datetime.datetime(2016, 10, 27, 18, 14, 54), [1, 2, 3]]
pickle模組
python的picklekle序列化。基本上功能使用和JSON模組沒有太大差別,方法也同樣是dumps/dump和loads/load。 cPickle是pickle模組的C語言編譯版本相對速度較快。
與JSON不同的是pickle不是用於多種語言間的資料傳輸,它僅作為python物件的持久化或python程式間進行互相傳輸物件的方法,因此它支援了python所有的資料類型。
pickle反序列化後的對象與原對像是等值的副本對象,類似與deepcopy。
dumps/dump序列化
from datetime import date try: import cPickle as pickle #python 2 except ImportError as e: import pickle #python 3 src_dic = {"date":date.today(),"oth":([1,"a"],None,True,False),} det_str = pickle.dumps(src_dic) print det_str # (dp1 # S'date' # p2 # cdatetime # date # p3 # (S'\x07\xe0\n\x1b' # tRp4 # sS'oth' # p5 # ((lp6 # I1 # aS'a' # aNI01 # I00 # tp7 # s. with open(r"c:\pickle.txt","w") as f: pickle.dump(src_dic,f)loads/load反序列化🎜
from datetime import date try: import cPickle as pickle #python 2 except ImportError as e: import pickle #python 3 src_dic = {"date":date.today(),"oth":([1,"a"],None,True,False),} det_str = pickle.dumps(src_dic) with open(r"c:\pickle.txt","r") as f: print pickle.load(f) # {'date': datetime.date(2016, 10, 27), 'oth': ([1, 'a'], None, True, False)}🎜JSON和pickle模組的區別🎜🎜1、JSON只能處理基本資料類型。 pickle能處理所有Python的資料類型。 🎜🎜2、JSON用於各種語言之間的字元轉換。 pickle用於Python程式物件的持久化或Python程式間物件網路傳輸,但不同版本的Python序列化可能還有差異。 🎜🎜🎜🎜

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

choosearraysoverlistsinpythonforbetterperformanceandmemoryfliceSpecificScenarios.1)largenumericaldatasets:arraysreducememoryusage.2)績效 - 臨界雜貨:arraysoffersoffersOffersOffersOffersPoostSfoostSforsssfortasssfortaskslikeappensearch orearch.3)testessenforcety:arraysenforce:arraysenforc

在Python中,可以使用for循環、enumerate和列表推導式遍歷列表;在Java中,可以使用傳統for循環和增強for循環遍歷數組。 1.Python列表遍歷方法包括:for循環、enumerate和列表推導式。 2.Java數組遍歷方法包括:傳統for循環和增強for循環。

本文討論了版本3.10中介紹的Python的新“匹配”語句,該語句與其他語言相同。它增強了代碼的可讀性,並為傳統的if-elif-el提供了性能優勢

Python中的功能註釋將元數據添加到函數中,以進行類型檢查,文檔和IDE支持。它們增強了代碼的可讀性,維護,並且在API開發,數據科學和圖書館創建中至關重要。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Dreamweaver CS6
視覺化網頁開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器