Python 中元组的连接运算符如何工作?
元组是 Python 对象的集合,这些对象由逗号分隔,是有序且不可变的。元组与列表一样,都是序列。元组和列表之间的区别在于,元组与列表不同,元组不能更改,元组使用圆括号,而列表使用方括号。
tup=('tutorials', 'point', 2022,True)
print(tup)
如果您执行上述代码段,将产生以下输出:
('tutorials', 'point', 2022, True)
在本文中,我们将了解连接运算符在 Python 中如何作用于元组。
元组的连接操作
Python 中的元组连接是指将两个或多个元组连接起来形成单个元组。有多种方法可以执行两个元组的连接。下面讨论了其中两种方法。
- 使用“+”运算符。
- 使用 sum() 函数。
使用“+”运算符
当需要连接多个元组时,可以使用“+”运算符。元组是一种不可变数据类型。这意味着一旦定义了值,就无法通过访问其索引元素来更改它。如果尝试更改元素,我们会得到一个错误。它们至关重要,因为它们保证了只读访问。
“+”运算符可用于连接文本或添加数值。
示例
以下示例演示了如何使用“+”运算符连接元组。
tuple_1 = (11, 14, 0, 78, 33, 11)
tuple_2 = (10, 78, 0, 56, 8, 34)
print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)
result = tuple_1 + tuple_2
print("The tuple after concatenation is : " )
print(result)
输出
以上代码的输出如下:
The first tuple is : (11, 14, 0, 78, 33, 11) The second tuple is : (10, 78, 0, 56, 8, 34) The tuple after concatenation is : (11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)
使用 sum() 函数。
还有另一种解决此问题的方法,我们使用 sum() 函数连接元组。sum() 函数以两个元组作为参数,并返回一个单个元组,该元组是这两个元组的连接。
示例
在以下示例代码中,我们使用 sum() 函数连接两个元组。
tuple_1 = (11, 14, 0, 78, 33, 11)
tuple_2 = (10, 78, 0, 56, 8, 34)
print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)
result = sum((tuple_1, tuple_2), ())
print("The tuple after concatenation is : " )
print(result)
输出
以上代码将产生以下输出。
The first tuple is : (11, 14, 0, 78, 33, 11) The second tuple is : (10, 78, 0, 56, 8, 34) The tuple after concatenation is : (11, 14, 0, 78, 33, 11, 10, 78, 0, 56, 8, 34)
使用 list() 和 extend() 方法
Python 中列表的 extends() 方法用于添加两个列表。要使用这些方法连接两个元组
- 使用 list() 方法将元组转换为列表。
- 使用 extend() 方法添加这两个列表。
示例
以下是一个使用 list() 和 extend() 方法连接两个数组的示例:
tuple1 = ('JavaFX', 'OpenCV','CoffeeScript')
tuple2 = ('Hadoop', 'Spark')
print("Contents of tuple1 : " + str(tuple1))
print("Contents of tuple2 : " + str(tuple2))
list1=list(tuple1)
list1.extend(tuple2)
print("Result : " + str(list1))
输出
Contents of tuple1 : ('JavaFX', 'OpenCV', 'CoffeeScript')
Contents of tuple2 : ('Hadoop', 'Spark')Result : ['JavaFX', 'OpenCV', 'CoffeeScript', 'Hadoop', 'Spark']
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP