如何在 Python 元组中附加元素?
programmingpythonserver side programming更新于 2024/12/27 0:12:17
Python 中的元组是不可变的,这意味着一旦创建,其内容就无法更改。但是,有时我们想要更改现有的元组,在这种情况下,我们必须仅使用原始元组中更改的元素来创建新的元组。
以下是元组的示例 -
s = (4,5,6) print(s) print(type(s))
以下是上述代码的输出 −
(4, 5, 6)<class 'tuple'>
Tuple 是不可变的,尽管您可以使用 + 运算符连接多个元组。此时旧对象仍然存在,并创建一个新对象。
在 Tuple 中附加元素
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)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

