Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การทำ XOR Operation บน Tuple ใน Python

Tuple XOR Operation ใน Python

เมื่อต้องการทำ Operation XOR (Exclusive OR) บน Tuple สองตัวแบบ Element-wise สามารถใช้ zip() และ Generator Expression ได้

XOR Operator (^)

ใน Python ใช้ ^ สำหรับ Bitwise XOR เปรียบเทียบ Bit ตรงกัน: ต่างกันให้ 1, เหมือนกันให้ 0

ตัวอย่างโค้ด

my_tuple_1 = (7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 0)

print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)

# zip จับคู่ แล้ว XOR กัน
my_result = tuple(elem_1 ^ elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The XORed tuple value is : ")
print(my_result)

ผลลัพธ์

The first tuple is : (7, 8, 3, 4, 3, 2)
The second tuple is : (9, 6, 8, 2, 1, 0)
The XORed tuple value is : (14, 14, 11, 6, 2, 2)

คำอธิบาย

  • กำหนด Tuple 2 ตัว และแสดงผล
  • ใช้ zip() จับคู่ Element ที่ Index ตรงกัน
  • Generator Expression ทำ XOR (elem_1 ^ elem_2)
  • แปลงเป็น Tuple ด้วย tuple()
  • เก็บผลลัพธ์และแสดง

การคำนวณ XOR แบบ Binary

IndexTuple 1 (Binary)Tuple 2 (Binary)XOR ResultDecimal
07 = 01119 = 1001111014
18 = 10006 = 0110111014
23 = 00118 = 1000101111
34 = 01002 = 001001106
43 = 00111 = 000100102
52 = 00100 = 000000102

Bitwise Operators อื่นๆ

# AND (&)
tuple(a & b for a, b in zip(t1, t2))

# OR (|)
tuple(a | b for a, b in zip(t1, t2))

# NOT (~) - Unary
tuple(~a for a in t1)

# Left Shift (<<)
tuple(a << 1 for a in t1)

# Right Shift (>>)
tuple(a >> 1 for a in t1)

ใช้ NumPy

import numpy as np
result = tuple(np.bitwise_xor(np.array(t1), np.array(t2)))