将 Set 转换为 Tuple 并将 Tuple 转换为 Set 的 Python 程序
当需要将集合结构转换为元组,将元组转换为集合时,可以使用'tuple'和'set'方法。
以下是相同的演示-
示例
my_set = {'ab', 'cd', 'ef', 'g', 'h', 's', 'v'}
print("类型是: ")
print(type(my_set), " ", my_set)
print("Converting a set into a tuple")
my_tuple = tuple(my_set)
print("类型是: ")
print(type(my_tuple), " ", my_tuple)
my_tuple = ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
print("元组是:")
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)输出结果类型是:{'ef', 'g', 'h', 's', 'ab', 'v', 'cd'} Converting a set into a tuple 类型是: ('ef', 'g', 'h', 's', 'ab', 'v', 'cd') 元组是: ('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'}
解释
一个集合被定义并显示在控制台上。
此数据结构的类型使用“类型”方法确定。
使用'tuple'方法将其转换为元组。
这种类型的类型是使用'type'方法确定的。
现在要将这个元组转换回set,使用'set'方法。
此类型已确定并显示为控制台上的输出。