python的内置数据结构可变不可变_如何在Python中实现不可变的数据结构?
问题
您需要在Python中实现不可变的数据结构。
介绍..
当您要防止多个人同时在并行编程中修改一条数据时,不可变数据结构非常方便。可变数据结构(例如Array)可以随时更改,而可变数据结构则不能更改。
怎么做..
让我逐步向您展示如何处理不可变和可变的数据结构。
示例# STEP 01 - Create a Mutable array.
# Define an array
atp_players = ['Murray', 'Nadal', 'Djokovic']
print(f" *** Original Data in my array is - {atp_players}")
***我数组中的原始数据是-['Murray', 'Nadal', 'Djokovic']
# Changing the player name from Murray to Federer
atp_players[0] = 'Federer'
print(f" *** Modified Data in my array is - {atp_players}")
***我数组中的修改数据是-['Federer', 'Nadal', 'Djokovic']
结论
我们已经能够像更改数组值一样,如果您是该数组的独占用户,这可能会很有用。但是,在实时生产中,多个程序可能正在使用此数组进行更改,并可能导致意外的数据。
另一方面,元组的行为有所不同,请看下面的例子。# STEP 02 - Try changing a Tuple
try:
atp_players_tuple = ('Murray', 'Nadal', 'Djokovic')
print(f" *** Original Data in my tuple is - {atp_players_tuple}")
atp_players_tuple[0] = 'Federer'
except Exception as error:
print(f" *** Tried modifying data but ended up with - {error}")
*** Original Data in my tuple is - ('Murray', 'Nadal', 'Djokovic')
*** Tried modifying data but ended up with - 'tuple' object does not support item assignment
结论:
您在上面看到的是,元组不能被修改对吗?但是,有一个例外,如果元组中包含数组,则可以更改值。atp_players_array_in_tuple = (['Murray'], ['Nadal'], ['Djokovic'])
print(f" *** Original Data in my tuple with arrays is - {atp_players_array_in_tuple}")
atp_players_array_in_tuple[0][0] = 'Federer'
print(f" *** Modified Data in my tuple with arrays is - {atp_players_array_in_tuple}")
*** Original Data in my tuple with arrays is - (['Murray'], ['Nadal'], ['Djokovic'])
*** Modified Data in my tuple with arrays is - (['Federer'], ['Nadal'], ['Djokovic'])
那么如何保护数据呢?嗯,只需将数组转换为元组即可。try:
atp_players_tuple_in_tuple = (('Murray'), ('Nadal'), ('Djokovic'))
print(f" *** Original Data in my tuple is - {atp_players_tuple_in_tuple}")
atp_players_tuple_in_tuple[0] = 'Federer'
except Exception as error:
print(f" *** Tried modifying data in my tuple but ended up with - {error}")
*** Original Data in my tuple is - ('Murray', 'Nadal', 'Djokovic')
*** Tried modifying data in my tuple but ended up with - 'tuple' object does not support item assignment
还有更多.. Python有一个很棒的内置工具,名为NamedTuple。您可以扩展该类以创建构造函数。让我们以编程方式理解。# Create a simple class on Grandslam titles in pythons way.
class GrandSlamsPythonWay:
def __init__(self, player, titles):
self.player = player
self.titles = titles
stats = GrandSlamsPythonWay("Federer", 20)
print(f" *** Stats has details as {stats.player} - {stats.titles}")
*** Stats has details as Federer - 20
您如何看待这个课程,这是一成不变的吗?让我们将Federer更改为Nadal进行检查。stats.player = 'Nadal'
print(f" *** Stats has details as {stats.player} - {stats.titles}")
*** Stats has details as Nadal - 20
因此,这毫无疑问是一个不变的数据结构,因为我们能够将Federer更新为Nadal。现在,让我们使用NamedTuple创建一个类,看看它的默认行为是什么。from typing import NamedTuple
class GrandSlamsWithNamedTuple(NamedTuple):
player: str
titles: int
stats = GrandSlamsWithNamedTuple("Federer", 20)
print(f" *** Stats has details as {stats.player} - {stats.titles}")
stats.player = 'Djokovic'
print(f" *** Stats has details as {stats.player} - {stats.titles}")
*** Stats has details as Federer - 20
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in
10 print(f" *** Stats has details as {stats.player} - {stats.titles}")
11
---> 12 stats.player = 'Djokovic'
13 print(f" *** Stats has details as {stats.player} - {stats.titles}")
AttributeError: can't set attribute
德约科维奇似乎不得不再等一段时间才能获得20个大满贯冠军。
但是,我们可以使用_replace方法进行复制并在_replace期间更新值。djokovic_stats = stats._replace(player="Djokovic", titles=17)
print(f" *** djokovic_stats has details as {djokovic_stats.player} - {djokovic_stats.titles}")
*** djokovic_stats has details as Djokovic - 17
示例
最后,我将举一个涵盖以上所有内容的示例。
对于此示例,假设我们正在为蔬菜店编写软件。from typing import Tuple
# Create a Class to represent one purchase
class Prices(NamedTuple):
id: int
name: str
price: int # Price in dollars
# Create a Class to track the purchase
class Purchase(NamedTuple):
purchase_id: int
items: Tuple[Prices]
# Create vegetable items and their corresponding prices
carrot = Prices(1, "carrot", 2)
tomato = Prices(2, "tomato", 3)
eggplant = Prices(3, "eggplant", 5)
# Now let say our first cusotmer Mr.Tom had purchased carrot and tomato
tom_order = Purchase(1, (carrot, tomato))
# Know the total cost we need to charge Mr.Tom
total_cost = sum(item.price for item in tom_order.items)
print(f"*** Total Cost from Mr.Tom is - {total_cost}$")
输出结果*** Total Cost from Mr.Tom is - 5$
python的内置数据结构可变不可变_如何在Python中实现不可变的数据结构?相关推荐
- java创建一个不可变对象_如何在Java中创建不可变类?
java创建一个不可变对象 Today we will learn about the immutable class in Java. What are immutable classes? The ...
- python的内置数据结构_Python基础知识2-内置数据结构(上)
分类 数值型 用浮点型的时候注意别和"=="一起使用. 数字的处理函数 注意round()函数的特殊:四舍六入五取偶 类型判断 列表list 列表list定义 初始化 列表索引访问 ...
- golang判断结构体为空_如何在Golang中检查结构是否为空?
golang判断结构体为空 The size of an empty structure is zero in Golang. Here, empty structure means, there i ...
- python标准库math中用来计算平方根_如何在python中计算平方根?
这可能是晚了一点回答,但最简单而准确的方法来计算平方根是牛顿的方法. 你有一个数字,你想要计算它的平方根(num),你猜它的平方根(estimate).估计值可以是大于0的任何数字,但有意义的数字会显 ...
- python从数据库取数据 显示字段名_如何在python中将SQL数据库中的字段名放入列表中...
以下是我目前掌握的代码:from ConfigParser import * import MySQLdb configuration = ConfigParser() configuration.r ...
- python内置数据结构教程_python课程第二周 内置数据结构——列表和元组
5种内置数据结构:列表.元组.字典.集合.字符串.列表.字典.字符串三种被称为线性结构.针对线性结构的操作有:切片.封包和解包.成员运算符.迭代. 针对数据结构的操作有解析式:解析式分为列表解析.生成 ...
- python数据结构与算法面试_python面试总结4(算法与内置数据结构)
算法与内置数据结构 常用算法和数据结构 sorted dict/list/set/tuple 分析时间/空间复杂度 实现常见数据结构和算法 数据结构/算法 语言内置 内置库 线性结构 list(列表) ...
- python数据结构的列表_Python内置数据结构——列表list
内置数据结构分类: 数值型 int , float , complex , bool 序列对象 字符串 str 列表 list tuple(元组) 键值对 集合 set 字典 dict 数字型int ...
- python类型-Python基本内置数据类型有哪些?
玩蛇网Python学习平台在这里会和大家讲下Python初学者,最常用到的Python基本内置数据类型有哪些. 在Python程序中,每个数据都是对像,每个对像都有自己的一个类型.不同类型有不同的操作 ...
最新文章
- vim学习笔记(一)
- 国学早教视频 16G
- settimeout( )是全局函数吗_JS函数的执行
- Angular自学笔记(?)属性型指令
- pycharm变量存_pycharm不为人知的功能们
- 学生成绩统计c语言课程设计,学生成绩管理系统-C语言课程设计
- tshark 和 tcpdump 的区别
- 微软直播马上开始,近百岗位等你来,快戳进直播间
- 查看Oracle当前用户下的信息
- Illustrator教程,如何在 Illustrator 中创建和应用图案?
- 三 APPIUM Android自动化 测试初体验(转)
- 面试:用 Java 实现一个 Singleton 模式
- comsol兼容服务器系统,comsol 云服务器
- 【每日一题】一起冲击蓝桥杯吧——Day3【蓝桥真题一起练】
- 云流化像素流技术解决方案之虚拟仿真系统
- 【something】简单的平均脸制作
- 如何修改wamp5的端口号,默认页。
- 【学习小结】树上的概率、期望问题,树上高斯消元
- 装在笔记本里的私有云环境:网络存储篇(中)
- 中国大学MOOC哈工大C语言程序设计第9周编程题在线测试
热门文章
- 2005年最具发展潜力的十大职业
- 中国大豆产业的“退化”路径
- #C++# #likely# #unlikely#减少CPU流水线分支预测错误带来的性能损失
- SharePoint 命令 安装、部署、回收、删除、更新 wsp包 (Solution)
- 徐小明:周五操作策略
- 论文阅读 [TPAMI-2022] Augmentation Invariant and Instance Spreading Feature for Softmax Embedding
- 如何使用JQuery实现Js二级联动和三级联动
- [附源码]java毕业设计火车票预订系统论文2022
- 【转】“Microsoft Office Word已停止工作”的终极解决方案
- 2021-2027中国屏幕保护膜市场现状及未来发展趋势