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

Python示例:向元组中添加一个项

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

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

标签: 红包