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

โปรแกรม Python แปลง Set เป็น Tuple และ Tuple เป็น Set


ภาพรวม

เมื่อต้องการแปลงโครงสร้าง Set เป็น Tuple และ Tuple เป็น Set สามารถใช้เมธอด tuple() และ set()

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

my_set = {'ab', 'cd', 'ef', 'g', 'h', 's', 'v'}
print("The type is : ")
print(type(my_set), " ", my_set)
print("Converting a set into a tuple")
my_tuple = tuple(my_set)
print("The type is : ")
print(type(my_tuple), " ", my_tuple)
my_tuple = ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
print("The tuple is:")
print(my_tuple)
print(type(my_tuple), " ", my_tuple)
print("Converting tuple to set")
my_set = set(my_tuple)
print(type(my_set), " ", my_set)

ผลลัพธ์ตัวอย่าง

The type is :  {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}
Converting a set into a tuple
The type is :  ('ef', 'g', 'h', 's', 'ab', 'v', 'cd')
The tuple is:
('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
 ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
Converting tuple to set
 {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}

คำอธิบาย

  • นิยาม Set และแสดงบนคอนโซล
  • กำหนดประเภทข้อมูลด้วยเมธอด type()
  • แปลงเป็น Tuple ด้วยเมธอด tuple()
  • กำหนดประเภทของ Tuple ด้วย type()
  • แปลง Tuple กลับเป็น Set ด้วยเมธอด set()
  • กำหนดประเภทและแสดงผลลัพธ์บนคอนโซล