編寫一個 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)
原創文章,作者:0CPE0,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/126727.html