创建元组

元组是通过将所有项目(元素)放在括号内()并用逗号分隔来创建的。括号是可选的,但是使用它们是一种很好的做法。
一个元组可以有任意数量的项,它们可以是不同的类型(整数、浮点数、列表、字符串等)。

Different types of tuples # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, “Hello”, 3.4) print(my_tuple) # nested tuple my_tuple = (“mouse”, [8, 4, 6], (1, 2, 3)) print(my_tuple)
输出
() (1, 2, 3) (1, ‘你好’, 3.4) (‘鼠标’, [8, 4, 6], (1, 2, 3))
也可以在不使用括号的情况下创建元组。这被称为元组包装。

my_tuple = 3, 4.6, “dog” print(my_tuple) # tuple unpacking is also possible a, b, c = my_tuple print(a) # 3 print(b) # 4.6 print(c) # dog
输出
(3, 4.6, ‘狗’) 3 4.6 狗
用一个元素创建一个元组有点棘手。
括号内只有一个元素是不够的。我们需要一个尾随逗号来表明它实际上是一个元组。

my_tuple = (“hello”) print(type(my_tuple)) # # Creating a tuple having one element my_tuple = (“hello”,) print(type(my_tuple)) # # Parentheses is optional my_tuple = “hello”, print(type(my_tuple)) #
输出
<类’str’> <类’元组’> <类’元组’>


访问元组元素

我们可以通过多种方式访问元组的元素。

1. 索引

我们可以使用索引运算符[]访问元组中的项,其中索引从 0 开始。
因此,具有 6 个元素的元组将具有从 0 到 5 的索引。尝试访问元组索引范围(在本例中为 6,7,…)之外的索引将引发IndexError.
索引必须是整数,所以我们不能使用浮点数或其他类型。这将导致TypeError.
同样,嵌套元组使用嵌套索引访问,如下例所示。

Accessing tuple elements using indexing my_tuple = (‘p’,’e’,’r’,’m’,’i’,’t’) print(my_tuple[0]) # ‘p’ print(my_tuple[5]) # ‘t’ # IndexError: list index out of range # print(my_tuple[6]) # Index must be an integer # TypeError: list indices must be integers, not float # my_tuple[2.0] # nested tuple n_tuple = (“mouse”, [8, 4, 6], (1, 2, 3)) # nested index print(n_tuple[0][3]) # ‘s’ print(n_tuple[1][1]) # 4
输出
磷 吨 秒 4


2. 负索引

Python 允许对其序列进行负索引。
索引 -1 表示最后一项,-2 表示倒数第二项,依此类推。

Negative indexing for accessing tuple elements my_tuple = (‘p’, ‘e’, ‘r’, ‘m’, ‘i’, ‘t’) # Output: ‘t’ print(my_tuple[-1]) # Output: ‘p’ print(my_tuple[-6])

输出
吨 磷


3.切片

我们可以使用切片运算符冒号访问元组中的一系列项目:。

Accessing tuple elements using slicing my_tuple = (‘p’,’r’,’o’,’g’,’r’,’a’,’m’,’i’,’z’) # elements 2nd to 4th # Output: (‘r’, ‘o’, ‘g’) print(my_tuple[1:4]) # elements beginning to 2nd # Output: (‘p’, ‘r’) print(my_tuple[:-7]) # elements 8th to end # Output: (‘i’, ‘z’) print(my_tuple[7:]) # elements beginning to end # Output: (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’) print(my_tuple[:])
输出
(‘r’, ‘o’, ‘g’) (‘p’, ‘r’) (‘i’, ‘z’) (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’)
通过考虑元素之间的索引,可以最好地可视化切片,如下所示。所以如果我们想访问一个范围,我们需要一个索引来从元组中切出该部分。
image.png
Python中的元素切片


更改元组

与列表不同,元组是不可变的。
这意味着元组的元素一旦被分配就不能更改。但是,如果元素本身是像列表这样的可变数据类型,则可以更改其嵌套项。
我们还可以将元组分配给不同的值(重新分配)。

Changing tuple values my_tuple = (4, 2, 3, [6, 5]) # TypeError: ‘tuple’ object does not support item assignment # my_tuple[1] = 9 # However, item of mutable element can be changed my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5]) print(my_tuple) # Tuples can be reassigned my_tuple = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’) # Output: (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’) print(my_tuple)
输出
(4, 2, 3, [9, 5]) (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’)
我们可以使用+运算符来组合两个元组。这称为串联
我们还可以使用运算符将元组中的元素重复给定次数
无论+和
操作会导致新的记录。

Concatenation # Output: (1, 2, 3, 4, 5, 6) print((1, 2, 3) + (4, 5, 6)) # Repeat # Output: (‘Repeat’, ‘Repeat’, ‘Repeat’) print((“Repeat”,) 3)
*输出

(1, 2, 3, 4, 5, 6) (‘重复’, ‘重复’, ‘重复’)


删除元组

如上所述,我们不能更改元组中的元素。这意味着我们不能从元组中删除或移除项目。
但是,可以使用关键字del完全删除元组。

Deleting tuples my_tuple = (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’) # can’t delete items # TypeError: ‘tuple’ object doesn’t support item deletion # del my_tuple[3] # Can delete an entire tuple del my_tuple # NameError: name ‘my_tuple’ is not defined print(my_tuple)
输出
回溯(最近一次调用最后一次): 文件“”,第 12 行,在 中 NameError:未定义名称“my_tuple”


元组方法

添加项目或删除项目的方法不适用于元组。只有以下两种方法可用。
Python 元组方法的一些示例:

my_tuple = (‘a’, ‘p’, ‘p’, ‘l’, ‘e’,) print(my_tuple.count(‘p’)) # Output: 2 print(my_tuple.index(‘l’)) # Output: 3
输出
2 3


其他元组操作

1.元组成员测试

我们可以使用关键字 测试一个项目是否存在于元组中in。

Membership test in tuple my_tuple = (‘a’, ‘p’, ‘p’, ‘l’, ‘e’,) # In operation print(‘a’ in my_tuple) print(‘b’ in my_tuple) # Not in operation print(‘g’ not in my_tuple)
输出
真的 错误的 真的


2. 遍历元组

我们可以使用for循环来遍历元组中的每个项目。

Using a for loop to iterate through a tuple for name in (‘John’, ‘Kate’): print(“Hello”, name)
输出
你好约翰 你好凯特


元组优于列表的优势

由于元组与列表非常相似,因此它们都用于类似的情况。但是,在列表上实现元组有某些优点。下面列出了一些主要优点:

  • 我们通常对异构(不同)数据类型使用元组,对同类(相似)数据类型使用列表。
  • 由于元组是不可变的,迭代元组比使用列表更快。所以有轻微的性能提升。
  • 包含不可变元素的元组可以用作字典的键。对于列表,这是不可能的。
  • 如果您有不变的数据,将其实现为元组将保证它保持写保护。