首页 > 编程知识 正文

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

时间:2023-11-24 15:33:42 阅读:308928 作者:LHKY

编写一个 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)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。