Python 如何在元组中添加元素
Python中的元组是不可变的,意味着一旦创建后,它们的内容就无法更改。然而,在某些情况下,我们希望改变现有的元组,这种情况下必须使用原始元组中仅有的更改元素创建一个新的元组。
以下是元组的示例:
s = (4,5,6)
print(s)
print(type(s))
以下是以上代码的输出−
(4, 5, 6)
<class 'tuple'>
元组是不可变的,尽管你可以使用 + 运算符来连接多个元组。在这一点上,旧对象仍然存在,并且创建了一个新对象。
在元组中追加元素
元组是不可变的,尽管你可以使用 + 运算符来连接多个元组。在这一点上,旧对象仍然存在,并且创建了一个新对象。
示例
以下是一个追加元组的示例 –
s=(2,5,8)
s_append = s + (8, 16, 67)
print(s_append)
print(s)
输出
以下是上述代码的输出结果:
(2, 5, 8, 8, 16, 67)
(2, 5, 8)
注意 − 连接仅适用于元组。不能与其他类型(例如列表)连接。
示例
以下是将元组与列表连接的示例−
s=(2,5,8)
s_append = (s + [8, 16, 67])
print(s_append)
print(s)
输出
上述代码的输出如下错误信息:
Traceback (most recent call last):
File "main.py", line 2, in <module>
s_append = (s + [8, 16, 67])
TypeError: can only concatenate tuple (not "list") to tuple
连接只有一个元素的元组
如果你想要向一个元组添加一个项,你可以连接一个只有一个元素的元组。
示例
以下是连接只有一个元素的元组的示例:
s=(2,5,8)
s_append_one = s + (4,)
print(s_append_one)
输出
以下是上述代码的输出结果。
(2, 5, 8, 4)
注意 − 一个只有一个元素的元组的末尾必须包含逗号,如上例所示。
在元组中添加/插入项目
您可以通过在开头或结尾添加新项目来连接元组,但是,如果您希望在任何位置插入新项目,则必须将元组转换为列表。
示例
以下是在元组中添加项目的示例−
s= (2,5,8)
# Python conversion for list and tuple to one another
x = list(s)
print(x)
print(type(x))
# Add items by using insert ()
x.insert(5, 90)
print(x)
# Use tuple to convert a list to a tuple ().
s_insert = tuple(x)
print(s_insert)
print(type(s_insert))
输出
我们得到了上述代码的以下输出。
[2, 5, 8]
class 'list'>
[2, 5, 8, 90]
(2, 5, 8, 90)
class 'tuple'>
使用append()方法
使用append()方法将一个新元素添加到列表的末尾。
示例
以下是使用append()方法添加元素的示例:
# converting tuple to list
t=(45,67,36,85,32)
l = list(t)
print(l)
print(type(l))
# appending the element in a list
l.append(787)
print(l)
# Converting the list to tuple using tuple()
t=tuple(l)
print(t)
输出
下面是上述代码的输出结果。
[45, 67, 36, 85, 32]
class 'list'>
[45, 67, 36, 85, 32, 787]
(45, 67, 36, 85, 32, 787)