当前分类:300例题>>正文

Python示例:从元组中移除项目

来源:互联网   更新时间:2023年6月23日  

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)
本文固定链接:https://6yhj.com/leku-p-4414.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: chatgpt