您的位置:

Python 程序:从元组中移除项目

编写一个 Python 程序,从元组中移除或删除一个项目。在 Python 中,我们不能从元组中删除一个项目。相反,我们必须将其分配给一个新的元组。在这个例子中,我们使用元组切片和连接来移除元组项。第一个,numtup[:3]+numtup[4:]删除了第三个元组项。

# Remove an Item from Tuple

numTuple = (9, 11, 22, 45, 67, 89, 15, 25, 19)
print("Tuple Items = ", numTuple)

numTuple = numTuple[:3] + numTuple[4:]
print("After Removing 4th Tuple Item = ", numTuple)

numTuple = numTuple[:5] + numTuple[7:]
print("After Removing 5th and 6th Tuple Item = ", numTuple)

Python 中的另一个选项是将 Tuple 转换为列表,并使用移除函数,而不是移除列表项。接下来,转换回元组。

# Remove an Item from Tuple

numTuple = (2, 22, 33, 44, 5, 66, 77)
print("Tuple Items = ", numTuple)

numList = list(numTuple)
numList.remove(44)

numTuple1 = tuple(numList)
print("After Removing 3rd Tuple Item = ", numTuple1)
Tuple Items = (2, 22, 33, 44, 5, 66, 77)
After Removing 3rd Tuple Item = (2, 22, 33, 5, 66, 77)