Python 轉換集合到元組和元組到集合的程式


當需要將集合結構轉換為元組,並將元組轉換為集合時,可以使用“元組”和“集合”方法。

以下是對其進行演示:

示例

 實戰演示

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 :
<class 'set'> {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}
Converting a set into a tuple
The type is :
<class 'tuple'> ('ef', 'g', 'h', 's', 'ab', 'v', 'cd')
The tuple is:
('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
<class 'tuple'> ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
Converting tuple to set
<class 'set'> {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}

說明

  • 定義了一個集合,並顯示在控制檯上。

  • 使用“型別”方法確定此資料結構的型別。

  • 使用“元組”方法將其轉換為元組。

  • 使用“型別”方法確定此型別的型別。

  • 現在要將此元組轉換回集合,請使用“集合”方法。

  • 確定此型別,並將其作為輸出顯示在控制檯上。

更新日期:14-4-2021

577 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告