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 operations
import 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 ”操作。在不可变容器(例如字符串、数字和元组)的情况下执行分配。

4. imul()  :- 该函数用于分配和乘以当前值。该操作执行“ a=b* ”操作。在不可变容器(例如字符串、数字和元组)的情况下执行分配。

# 演示 isub() 和 imul() 工作的 Python 代码

# importing operator to handle operator operations
import 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 operations
import operator

# 使用 itruediv() 进行除法赋值
x = operator.itruediv(10, 5);

# 打印修改后的值
print (\"除法赋值后的值:\", end=\"\")
print (x)

# 使用 imod() 取模并赋值
x = operator.imod(10, 6);

# 打印修改后的值
print (\"取模赋值后的值:\", end=\"\")
print (x)

输出:

除法赋值后的值:2.0
取模赋值后的值:4

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容