Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Toán tử Inplace trong Python


Định nghĩa - Toán tử In-place là phép toán thay đổi trực tiếp nội dung của linear algebra, vector, matrices (Tensor) đã cho mà không tạo bản sao. Các toán tử giúp thực hiện phép toán này gọi là inplace operator.

Ví dụ: a += b tương đương a = operator.iadd(a, b)

Có một số toán tử dùng cho In-place operation:

iadd()

Hàm này gán giá trị hiện tại và cộng thêm. Thực hiện phép x+=y. Trong trường hợp string, số thì gán không thực hiện.

Ví dụ

a = operator.iadd(1, 3)
print("The result after adding: ", end="")
print(a)

Kết quả

The result after adding: 5

isub()

Hàm này gán giá trị hiện tại và trừ. Thực hiện x-=y. Với string, số thì không gán.

Ví dụ

a = operator.isub(8, 6)
print("The result after subtracting: ", end="")
print(a)

Kết quả

The result after subtracting: 2

imul()

Hàm này gán giá trị hiện tại và nhân. Thực hiện x*=y. Với string, số thì không gán.

Ví dụ

a = operator.imul(8, 6)
print("The result after multiplying: ", end="")
print(a)

Kết quả

The result after multiplying: 48

itruediv()

Hàm này gán giá trị hiện tại và chia. Thực hiện x/=y. Với string, số thì không gán.

Ví dụ

a = operator.itruediv(54, 6)
print("The result after dividing: ", end="")
print(a)

Kết quả

The result after dividing: 9

imod()

Hàm này gán giá trị hiện tại và chia lấy dư. Thực hiện x%=y. Với string, số thì không gán.

Ví dụ

a = operator.imod(10, 5)
print("The result after modulus: ", end="")
print(a)

Kết quả

The result after modulus: 2.0

iconcat()

Hàm này nối hai chuỗi.

Ví dụ

a = "jupyter"
b = "notebook"
t = operator.iconcat(a, b)
print("After concatenation: ", end="")
print(t)

Kết quả

After concatenation: jupyter notebook