📜  Python中的就地运算符 |设置 1 (iadd()、isub()、iconcat()…)

📅  最后修改于: 2022-05-13 01:55:30.666000             🧑  作者: Mango

Python中的就地运算符 |设置 1 (iadd()、isub()、iconcat()…)

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

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

一些重要的就地操作

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

2. iconcat() :- 该函数用于在第二个末尾连接一个字符串。

# Python code to demonstrate the working of 
# iadd() and iconcat()
  
# importing operator to handle operator operations
import operator
  
# using iadd() to add and assign value
x = operator.iadd(2, 3);
  
# printing the modified value
print ("The value after adding and assigning : ", end="")
print (x)
  
# initializing values
y = "geeks"
  
z = "forgeeks"
  
# using iconcat() to concat the sequences
y = operator.iconcat(y, z)
  
# using iconcat() to concat sequences 
print ("The string after concatenation is : ", end="")
print (y)

输出:

The value after adding and assigning : 5
The string after concatenation is : geeksforgeeks

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

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

# Python code to demonstrate the working of 
# isub() and imul()
  
# importing operator to handle operator operations
import operator
  
# using isub() to subtract and assign value
x = operator.isub(2, 3);
  
# printing the modified value
print ("The value after subtracting and assigning : ", end="")
print (x)
  
# using imul() to multiply and assign value
x = operator.imul(2, 3);
  
# printing the modified value
print ("The value after multiplying and assigning : ", end="")
print (x)

输出:

The value after subtracting and assigning : -1
The value after multiplying and assigning : 6

5. itruediv() :- 该函数用于对当前值进行赋值和除法。此操作执行“ a/=b ”操作。在不可变容器的情况下执行分配,例如字符串、数字和元组。

6. imod() :- 该函数用于分配和返回余数。该操作执行“ a%=b ”操作。在不可变容器的情况下执行分配,例如字符串、数字和元组。

# Python code to demonstrate the working of 
# itruediv() and imod()
  
# importing operator to handle operator operations
import operator
  
# using itruediv() to divide and assign value
x = operator.itruediv(10, 5);
  
# printing the modified value
print ("The value after dividing and assigning : ", end="")
print (x)
  
# using imod() to modulus and assign value
x = operator.imod(10, 6);
  
# printing the modified value
print ("The value after modulus and assigning : ", end="")
print (x)

输出:

The value after dividing and assigning : 2.0
The value after modulus and assigning : 4

下一篇

  • Python中的就地运算符 |设置 2
  • 就地与标准运算符