您的位置:

Python 程序:向元组中添加一个项

编写一个 Python 程序向元组中添加一个条目。Python 元组不允许您向现有元组中添加项目。下面的 Python 示例将通过连接新项目和当前元组来创建一个新元组。

# Add an Item to Tuple

intTuple = (10, 20, 30, 40, 50)
print("Tuple Items = ", intTuple)

intTuple = intTuple + (70,)
print("Tuple Items = ", intTuple)

intTuple = intTuple + (80, 90)
print("Tuple Items = ", intTuple)

intTuple = intTuple[2:5] + (11, 22, 33, 44) + intTuple[7:]
print("Tuple Items = ", intTuple)

在这个 Python 示例中,我们允许用户输入 tuple 项,并将它们添加到一个空 Tuple 中。为了达到同样的目的,我们使用 for 循环范围来迭代元组项。

# Add an Item to Tuple

intTuple = ()

number = int(input("Enter the Total Number of Tuple Items = "))
for i in range(1, number + 1):
    value = int(input("Enter the %d Tuple value = " %i))
    intTuple = intTuple + (value,)

print("Tuple Items = ", intTuple)
Enter the Total Number of Tuple Items = 4
Enter the 1 Tuple value = 22
Enter the 2 Tuple value = 99
Enter the 3 Tuple value = 122
Enter the 4 Tuple value = 77
Tuple Items =  (22, 99, 122, 77)