你們對json應該很瞭解,是一種格式轉換的方式,怎麼在python中怎麼使用zip將list轉換爲json呢?瞭解過嗎,這篇小猿圈帶你學習一下這個技能。python
zip()函數將可迭代對象做爲參數,並打包成元組,返回的是一個個zip對象,能夠使用list或dict轉換返回結果,使用*zip能夠將打包的對象分解成列表。json
>>> l=[1,2,3,4] >>> keys=['a','b','c','d'] >>> zip(keys,l) <zip object at 0x000001E0AFA327C8> >>> dict(zip(keys,l)) {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> list(zip(keys,l)) [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # 若參數列表的長度不同,則以最短長度爲準 >>> m=[1,2,3] >>> list(zip(keys,m)) [('a', 1), ('b', 2), ('c', 3)] # 分解zip >>> a1,a2=zip(*zip(keys,l)) >>> a1 ('a', 'b', 'c', 'd') >>> a2 (1, 2, 3, 4) >>>
將二維列表轉成json函數
>>> import json >>> l=[[1,2,3,4],[5,6,7,8],[9,10,11,12]] >>> keys=['a','b','c','d'] >>> list_json=[dict(zip(keys,item)) for item in l] # indent縮進量,ensure_ascii=False支持中文 >>> str_json=json.dumps(list_json,indent=2, ensure_ascii=False) >>> print(str_json) [ { "a": 1, "b": 2, "c": 3, "d": 4 }, { "a": 5, "b": 6, "c": 7, "d": 8 }, { "a": 9, "b": 10, "c": 11, "d": 12 } ]
以上就是今天說的知識點,單看學會也不難,可是必定在實際項目、實際應用中必定要想到這個知識點,由於它能夠很方便的轉換爲json格式、因此平時必定要多練,讓它成爲本身的東西,也能夠寫一下本身的博客,這樣再看的時候知道當時是怎麼學的,小猿圈還有更多實用的知識點,直接百度搜索就能夠看到不少,但願對你有所幫助。學習