以逗号分隔的一组项目称为 Python 元组。元组的排序、固定项目和重复项在某种程度上与列表相似,但与列表不同的是,元组是不可变的。

两者之间的主要区别在于,一旦分配了元组的组成部分,就不能修改它们。另一方面,可以编辑列表的内容。

示例

("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.  

Python 元组的特点

  • 元组是一种不可变的数据类型,意味着在生成后无法更改其元素。
  • 元组中的每个元素都有一个特定的顺序,这个顺序永远不会改变,因为元组是有序序列。

创建元组:

所有的对象,也称为 "元素",必须用逗号分隔,并用括号 () 括起来。尽管括号不是必需的,但建议使用括号。

任何数量的项,包括具有不同数据类型(字典、字符串、浮点数、列表等)的项,都可以包含在元组中。

代码

# 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。如果我们试图访问超出元组范围的列表中的项,将引发索引错误。在这种情况下,超过四的索引将超出范围。

由于 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() 函数从元组返回所请求元素的第一个实例。

参数:

  • 要查找的项。
  • start:(可选)用于开始搜索的索引(可选)搜索的最后一个索引开始搜索的索引
  • 索引方法

代码

# 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)

元组相对于列表具有以下优点:

  • 元组所需的时间比列表少。
  • 由于元组,代码受到意外修改的保护。如果程序预期非变化信息,则最好将其存储在 "元组" 而不是 "列表" 中。元组中的数据是不可变的,而列表是可变的。
  • 如果元组包含不可变值(如字符串、数字或另一个元组),则可以将元组用作字典键。无法使用 "列表" 作为字典键,因为它们是可变的。

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程