Python 元组
以逗号分隔的一组项目称为Python元组。元组的排序、固定的项目和重复项在某种程度上类似于列表,但与列表不同,元组是不可变的。
两者之间的主要区别是一旦分配了元组的组成部分,我们就无法修改它们。另一方面,我们可以编辑列表的内容。
示例
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Python元组的特点
- Tuples是一种不可变的数据类型,意味着它们在生成后无法更改其元素。
- 元组中的每个元素都具有特定的顺序,该顺序永远不会改变,因为元组是有序序列。
形成一个元组
所有的对象(也称为”元素”)必须用逗号隔开,用括号()括起来。虽然括号不是必需的,但建议使用。
任何数量的项目,包括具有不同数据类型的项目(字典,字符串,浮点数,列表等),都可以包含在元组中。
代码
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
# Creating a tuple having objects of different data types
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
输出:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
括号在构建倍数时是不必要的。这被称为三连按。
代码
# Python program to create a tuple without using parentheses
# Creating a tuple
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
# Displaying the tuple created
print(tuple_)
# Checking the data type of object tuple_
print(type(tuple_) )
# Trying to modify tuple_
try:
tuple_[1] = 4.2
except:
print(TypeError )
输出:
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>
一个元组从一个孤立的部分发展起来可能会很复杂。
基本上缺少一个括号围绕着组件。必须用逗号分隔元素才能被识别为一个元组。
代码
# Python program to show how to create a tuple having a single element
single_tuple = ("Tuple")
print( type(single_tuple) )
# Creating a tuple that has only one element
single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )
输出:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
访问元组元素
元组的对象可以以多种方式访问。
索引
索引我们可以使用索引运算符[]来访问元组中的对象,索引从0开始。
具有五个项目的元组的索引范围为0到4。如果我们尝试获取超出元组范围的列表,则会引发索引错误。在这种情况下,索引大于4将超出范围。
由于Python中的索引必须是整数,我们不能提供浮点数据类型或任何其他类型的索引。如果我们提供浮点索引,结果将是TypeError。
可以通过嵌套元组访问元素的方法可以在下面的示例中看到。
代码
# Python program to show how to access tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
# Accessing the index of a nested tuple
print(nested_tuple[0][3])
print(nested_tuple[1][1])
输出:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
- 负索引
Python的序列对象支持负索引。
最后一项通过-1进行索引,倒数第二项通过-2进行索引,依此类推。
代码
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-1])
输出:
Element at -1 index: Collection
Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')
切片
元组切片是Python中常见的做法,也是程序员处理实际问题的常见方式。看看Python中的一个元组。切片一个元组以访问其各种元素。使用冒号作为直接切片操作符(:)是一种策略。
为了访问不同的元组元素,我们可以使用切片操作符冒号(:)。
代码
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
输出结果:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
删除元组
如前所述,元组的部分无法被修改。因此,我们无法消除或删除元组的组成部分。
然而,关键字 del 可以完全删除一个元组。
代码
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as e:
print(e)
输出:
'tuple' object does not support item deletion
name 'tuple_' is not defined
Python中的重复元组
代码
# Python program to show repetition in tuples
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
输出:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
元组方法
像列表一样,Python元组是一组不可变的对象。在Python中,有几种处理元组的方法。通过一些示例,本文将详细介绍这两种方法。
以下是一些这些方法的示例。
Count() 方法
count() 方法返回元组中预定组件出现的次数。
代码
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
print('Count of Java in T2 is:', res)
输出:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index()方法:
Index()函数返回Tuple中请求元素的第一个实例。
参数:
- 要查找的元素。
- 开始:(可选)用于开始最终(可选)搜索的索引:从中执行搜索的最近索引
- 索引方法
代码
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
输出:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
元组成员测试
利用关键字,我们可以确定给定的元组中是否存在某个项。
代码
# Python program to show how to perform membership test for tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
输出:
True
False
False
True
遍历元组
可以使用for循环来遍历每个元组元素。
代码
# Python program to show how to iterate over tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Iterating over tuple elements using a for loop
for item in tuple_:
print(item)
输出:
Python
Tuple
Ordered
Immutable
改变一个元组
元组是永久的物品,而不是记录。
这意味着一旦元组的元素被定义,我们就不能改变它们。然而,如果元素本身是一个可变的数据类型,比如列表,那么嵌套的元素可以被改变。
通过重新赋值,可以给元组分配多个值。
代码
# Python program to show that Python tuples are immutable objects
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
# Trying to change the element at index 2
try:
tuple_[2] = "Items"
print(tuple_)
except Exception as e:
print( e )
# But inside a tuple, we can change elements of a mutable object
tuple_[-1][2] = 10
print(tuple_)
# Changing the whole tuple
tuple_ = ("Python", "Items")
print(tuple_)
输出:
'tuple' object does not support item assignment
('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')
+运算符可以用于将多个元组组合成一个。这种现象被称为连接。
我们还可以使用*运算符将元组的元素重复预定次数。这已经在上面演示过了。
任务+和 *的后果是新元组。
代码
# Python program to show how to concatenate tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Adding a tuple to the tuple_
print(tuple_ + (4, 5, 6))
输出:
('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)
元组相对于列表具有以下优势:
- 元组比列表的操作时间更短。
- 由于元组的存在,代码可以避免被意外修改。如果程序需要存储不会改变的信息,最好使用“元组”而不是“记录”。
- 如果一个元组包含不可变的值,如字符串、数字或另一个元组,那么它可以用作字典的键。而”列表”不能被用作字典的键,因为它们是可变的。