Python运算符之Inplace运算符的使用教程

Python 在其定义中提供了执行就地操作的方法,即使用“ operator ”模块在单个语句中进行赋值和计算。 例如,

x += y is equivalent to x = operator.iadd(x, y)

一些重要的就地操作:
1. iadd():- 该函数用于分配和添加当前值。该操作执行“ a+=b ”操作。在不可变容器(例如字符串、数字和元组)的情况下不执行分配。
2. iconcat():- 该函数用于在第二个末尾连接一个字符串 。
# 演示 iadd() 和 iconcat() 工作的 Python 代码# importing operator to handle operator operationsimport operator# 使用 iadd() 添加和赋值x = operator.iadd(2, 3); # 打印修改后的值print ("添加赋值后的值为:", end="")print (x)# 初始化值y = "geeks"z = "forgeeks"# 使用 iconcat() 连接序列y = operator.iconcat(y, z)# 使用 iconcat() 连接序列print ("拼接后的字符串为:", end="")print (y)

输出:
添加赋值后的值为:5
拼接后的字符串为:geeksforgeeks
3. isub():- 该函数用于分配和减去当前值。该操作执行“ a-=b ”操作。在不可变容器(例如字符串、数字和元组)的情况下不执行分配。
【Python运算符之Inplace运算符的使用教程】4. imul():- 该函数用于分配和乘以当前值。该操作执行“ a=b* ”操作。在不可变容器(例如字符串、数字和元组)的情况下不执行分配。
# 演示 isub() 和 imul() 工作的 Python 代码# importing operator to handle operator operationsimport operator# 使用 isub() 减去和赋值x = operator.isub(2, 3); # 打印修改后的值print ("减法运算后的值:", end="")print (x)# 使用 imul() 进行乘法和赋值x = operator.imul(2, 3); # 打印修改后的值print ("乘法运算后的值:", end="")print (x)

输出:
减法运算后的值:-1
乘法运算后的值:6
5. itruediv():- 该函数用于对当前值进行赋值和除法。此操作执行“ a/=b ”操作。在不可变容器(例如字符串、数字和元组)的情况下不执行分配。
6. imod():- 该函数用于分配和返回余数。该操作执行“ a%=b ”操作。在不可变容器(例如字符串、数字和元组)的情况下不执行分配。
# 演示 itruediv() 和 imod() 工作的 Python 代码# importing operator to handle operator operationsimport operator# 使用 itruediv() 进行除法赋值x = operator.itruediv(10, 5); # 打印修改后的值print ("除法赋值后的值:", end="")print (x)# 使用 imod() 取模并赋值x = operator.imod(10, 6); # 打印修改后的值print ("取模赋值后的值:", end="")print (x)

输出:
除法赋值后的值:2.0
取模赋值后的值:4
到此这篇关于Python运算符之Inplace运算符的使用教程的文章就介绍到这了,更多相关Python Inplace运算符内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读