📜  Python – 清除元组

📅  最后修改于: 2022-05-13 01:54:54.769000             🧑  作者: Mango

Python – 清除元组

有时,在处理记录数据时,我们可能会遇到需要执行数据记录清除的问题。元组是不可变的,因此无法修改,因此使这项工作变得艰难。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 list() + clear() + tuple()
上述 3 个功能的组合可用于执行此任务。在此,我们将元组相互转换为列表,清除它并再次使用 tuple() 转换为元组。

Python3
# Python3 code to demonstrate
# Clearing a tuple
# using list() + tuple() + clear()
 
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Clearing a tuple
# using list() + tuple() + clear()
temp = list(test_tup)
temp.clear()
test_tup = tuple(temp)
 
# print result
print("The tuple after clearing values : " + str(test_tup))


Python3
# Python3 code to demonstrate
# Clearing a tuple
# using Reinitialization + tuple()
 
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Clearing a tuple
# using Reinitialization + tuple()
test_tup = tuple()
 
# print result
print("The tuple after clearing values : " + str(test_tup))


输出 :
The original tuple : (1, 5, 3, 6, 8)
The tuple after clearing values : ()


方法 #2:使用 tuple() 重新初始化
执行此任务的另一种直接方法是使用 tuple() 重新初始化元组,这将返回空元组。

Python3

# Python3 code to demonstrate
# Clearing a tuple
# using Reinitialization + tuple()
 
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Clearing a tuple
# using Reinitialization + tuple()
test_tup = tuple()
 
# print result
print("The tuple after clearing values : " + str(test_tup))
输出 :
The original tuple : (1, 5, 3, 6, 8)
The tuple after clearing values : ()