教程 > python 3 教程 > 阅读:1965

python3 向元组中添加元素——迹忆客-ag捕鱼王app官网

使用加法 ( ) 运算符将元素添加到元组,例如 new_tuple = my_tuple ('new', )。 元组是不可变的,因此为了向元组添加元素,我们必须创建一个包含该元素的新元组。

# 通过创建新元组将元素添加到元组
my_tuple = ('one', 'two')
new_tuple = my_tuple   ('three', )  #  逗号很重要
# ('one', 'two', 'three')
print(new_tuple)
# --------------------
# 通过重新分配将元素添加到元组
my_tuple_2 = ('one', 'two')
my_tuple_2  = ('three',)  #  逗号很重要
# ('one', 'two', 'three')
print(my_tuple_2)
# -------------------------
# 通过解包将元素添加到元组
my_tuple_3 = ('one', 'two')
my_str = 'three'
new_tuple_3 = (*my_tuple_3, my_str)
# ('one', 'two', 'three')
print(new_tuple_3)

代码示例显示了在 python 中将项目添加到元组的 3 种最常见的方法。

元组与列表非常相似,但实现的内置方法更少,并且是不可变的(无法更改)。

由于元组不能更改,将元素添加到元组的唯一方法是创建一个包含该元素的新元组。

第一个示例使用加法 ( ) 运算符通过组合 2 个其他元组来创建一个新元组。

my_tuple = ('one', 'two')
new_tuple = my_tuple   ('three', )  # 逗号很重要
# ('one', 'two', 'three')
print(new_tuple)

请注意,我们将值括在括号中并添加了一个尾随逗号,因此加法 ( ) 运算符左侧和右侧的值是元组。

# ('a', 'b', 'c')
print(('a', 'b')   ('c', ))

元组以多种方式构造:

  • 使用一对括号 () 创建一个空元组
  • 使用尾随逗号 - a 或 (a,)
  • 用逗号分隔项目 - a、b 或 (a, b)
  • 使用 tuple() 构造函数

尾随逗号很重要,是创建元组和字符串之间的区别。

print(type(('a',)))  # 
print(type(('a')))  # 

将元素添加到元组的另一种方法是使用重新分配。

my_tuple_2 = ('one', 'two')
my_tuple_2  = ('three',)  # 逗号很重要
# ('one', 'two', 'three')
print(my_tuple_2)

当我们不需要在添加元素之前访问元组的值时,这种方法很有用。

我们没有声明一个存储新元组的变量,而是为原始变量分配一个新值。

还可以通过将元组解压缩到新元组中来将项目添加到元组。

my_tuple_3 = ('one', 'two')
my_str = 'three'
new_tuple_3 = (*my_tuple_3, my_str)
# ('one', 'two', 'three')
print(new_tuple_3)

* 可迭代解包运算符使我们能够在函数调用、推导式和生成器表达式中解压缩可迭代对象。

example = (*(1, 2), 3)
#  (1, 2, 3)
print(example)

元组中的值被解压缩到一个新元组中,我们可以在其中添加额外的元素。

查看笔记

扫码一下
查看教程更方便
网站地图