一、用途
我们需要将内存中的数据进行序列化,即写入文件中时,写入的类型只能是字符串或者二进制类型。但是如果我们想要将复杂一些的数据类型,如:列表、字典或者函数之类的同样进行序列化,我们就要用到 json或者pickle。
二、json序列化
1、dumps序列化和loads反序列化
dumps把数据类型转换成字符串
import json info = { 'name': 'The Count of Monte Cristo', 'type': 'Movie' } data = json.dumps(info) print(data) print(type(data)) # 输出 {"name": "The Count of Monte Cristo", "type": "Movie"} <class 'str'>
loads把字符串转换成数据类型
import json get_info = json.loads(data) print(get_info['name']) print(get_info) print(type(get_info)) #输出 The Count of Monte Cristo {'name': 'The Count of Monte Cristo', 'type': 'Movie'} <class 'dict'>
2.dump序列化和load反序列化
dump把数据类型转换成字符串并存储在文件中
import json info = { 'name': 'The Count of Monte Cristo', 'type': 'Movie' } with open("test.txt", "w", encoding="utf-8") as f: json.dump(info, f) # 第一个参数是内存中的数据对象,第二个参数是文件句柄 #写入文件中的内容 {"name": "The Count of Monte Cristo", "type": "Movie"}
load把文件打开从字符串转换成数据类型
import json with open("test.txt", "r", encoding="utf-8") as f: data_from_file = json.load(f) print(data_from_file['name']) print(data_from_file) print(type(data_from_file)) #输出 The Count of Monte Cristo {'name': 'The Count of Monte Cristo', 'type': 'Movie'} <class 'dict'>
3.json序列化一个函数
import json def test(name): print("hello,{}".format(name)) info = { 'name': 'The Count of Monte Cristo', 'type': 'Movie', 'func': test } data = json.dumps(info) #输出 File "G:/python/untitled/study6/json&pickle模块.py", line 22, in <module> data = json.dumps(info) File "G:\python\install\lib\json\__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "G:\python\install\lib\json\encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "G:\python\install\lib\json\encoder.py", line 256, in iterencode return _iterencode(o, 0) File "G:\python\install\lib\json\encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: <function test at 0x0000021B13C57F28> is not JSON serializable
1、json只能处理简单的数据类型,例如:字典、列表、字符串等,不能处理函数等复杂的数据类型。
2、json是所有语言通用的,所有语言都支持json,如果我们需要python跟其他语言进行数据交互,那么就用json格式
三、pickle序列化
pickle的用法和上面的相同,但是pickle序列化后的数据类型是二进制的,并且pickle只能在python中是使用。
1.dumps && loads
import pickle def test(name): print("hello,{}".format(name)) info = { 'name': 'The Count of Monte Cristo', 'type': 'Movie', 'func': test } data = pickle.dumps(info) print(data) print(type(data)) #输出 b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x19\x00\x00\x00The Count of Monte Cristoq\x02X\x04\x00\x00\x00typeq\x03X\x05\x00\x00\x00Movieq\x04X\x04\x00\x00\x00funcq\x05c__main__\ntest\nq\x06u.' <class 'bytes'>
import pickle get_data = pickle.loads(data) get_data['func']('cat') print(get_data) #输出 hello,cat {'name': 'The Count of Monte Cristo', 'type': 'Movie', 'func': <function test at 0x00000235350A7F28>}
2. dump && load
import pickle def test(name): print("hello,{}".format(name)) info = { 'name': 'The Count of Monte Cristo', 'type': 'Movie', 'func': test } with open('test.txt', 'wb') as f: pickle.dump(info, f) # 写入test.txt文件中的内容 �}q (X typeqX MovieqX funcqc__main__ test qX nameqX The Count of Monte Cristoqu.
import pickle with open('test.txt', 'rb') as f: get_data = pickle.load(f) print(get_data) # 输出 {'name': 'The Count of Monte Cristo', 'func': <function test at 0x000001BA2AB4D510>, 'type': 'Movie'}
总结:
json值支持简单的数据类型,pickle支持所有的数据类型。
pickle只能支持python本身的序列化和反序列化,不能用作和其他语言做数据交互,而json可以。
pickle序列化的是整个的数据对象,所以反序列化函数时,函数体中的逻辑变了,是跟着心的函数体走的。
以上是内存中数据序列化实例的详细内容。更多信息请关注PHP中文网其他相关文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版
SublimeText3 Linux最新版

记事本++7.3.1
好用且免费的代码编辑器

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中