在Python中清除元组
Python|清除元组
在使用元组时,我们可能需要清除其元素/记录。在本教程中,我们将讨论一些清除元组的方法。
方法1:使用一对圆括号()重新初始化元组
可以使用一对圆括号()重新初始化一个非空的元组,以清除该元组。
#在Python中清除元组|方法1 #元组创建 x = ("Shivang", 21, "Indore", 9999867123) #打印原始元组 print("x: ", x) print("len(x): ", len(x)) print("type(x): ", type(x)) print() #通过使用重新初始化来清除元组 #一对圆括号“()”"()" x = () print("After clearing tuple....") print("x: ", x) print("len(x): ", len(x)) print("type(x): ", type(x)) print()
输出结果
x: ('Shivang', 21, 'Indore', 9999867123) len(x): 4 type(x): <class 'tuple'> After clearing tuple.... x: () len(x): 0 type(x): <class 'tuple'>
方法2:使用重新初始化元组tuple()
可以使用tuple()清除元组来重新初始化非空元组。
#在Python中清除元组|方法2 #元组创建 x = ("Shivang", 21, "Indore", 9999867123) #打印原始元组 print("x: ", x) print("len(x): ", len(x)) print("type(x): ", type(x)) print() #通过使用重新初始化来清除元组 "tuple()" x = tuple() print("After clearing tuple....") print("x: ", x) print("len(x): ", len(x)) print("type(x): ", type(x)) print()
输出结果
x: ('Shivang', 21, 'Indore', 9999867123) len(x): 4 type(x): <class 'tuple'> After clearing tuple.... x: () len(x): 0 type(x): <class 'tuple'>
方法3:将元组转换为列表,清除列表,然后再次将其转换为元组
由于元组没有任何库函数来清除其元素。我们可以1)使用list()方法将元组转换为列表,2)使用方法清除列表,3)使用函数再次将空列表转换为元组。此方法也可以用于清除元组。List.clear()tuple()
#在Python中清除元组|方法3 #元组创建 x = ("Shivang", 21, "Indore", 9999867123) #打印原始元组 print("x: ", x) print("len(x): ", len(x)) print("type(x): ", type(x)) print() #通过将元组转换为列表来清除元组, #清除清单,然后将其转换 #再次去元组 temp_list = list(x) #转换成清单 temp_list.clear() #清理清单 x = tuple(temp_list) #转换为元组 print("After clearing tuple....") print("x: ", x) print("len(x): ", len(x)) print("type(x): ", type(x))
输出结果
x: ('Shivang', 21, 'Indore', 9999867123) len(x): 4 type(x): <class 'tuple'> After clearing tuple.... x: () len(x): 0 type(x): <class 'tuple'>