Python 元组

元组是类似于 Python 列表的集合。主要区别在于,元组一旦创建就无法修改。


创建 Python 元组

我们通过将项目放在括号 () 中来创建元组。例如:

numbers = (1, 2, -5)
print(numbers) # Output: (1, 2, -5)

更多关于元组创建

使用 tuple() 构造函数创建元组

我们还可以使用 tuple() 构造函数创建元组。例如:

tuple_constructor = tuple(('Jack', 'Maria', 'David'))
print(tuple_constructor)

# Output: ('Jack', 'Maria', 'David')
不同类型的 Python 元组

以下是我们在 Python 中可以创建的不同类型的元组。

空元组

# create an empty tuple
empty_tuple = ()
print(empty_tuple)

# Output: ()

不同数据类型的元组

# tuple of string types
names = ('James', 'Jack', 'Eva')
print (names)

# tuple of float types
float_values = (1.2, 3.4, 2.1)
print(float_values)

混合数据类型的元组

# tuple including string and integer
mixed_tuple = (2, 'Hello', 'Python')
print(mixed_tuple)

# Output: (2, 'Hello', 'Python')

元组特性

元组是

  • 有序的 - 它们保持元素的顺序。
  • 不可变的 - 它们创建后不能更改。
  • 允许重复 - 它们可以包含重复值。

访问元组项

元组中的每个项都与一个数字关联,称为索引

索引总是从 0 开始,这意味着元组的第一个项在索引 0 处,第二个项在索引 1 处,依此类推。

Index of Tuple Item
元组项的索引

使用索引访问项

我们使用索引号访问元组项。例如:

languages = ('Python', 'Swift', 'C++')

# access the first item
print(languages[0])   # Python

# access the third item
print(languages[2])   # C++
Access Tuple Items
访问元组项

元组不能修改

Python 元组是不可变的(不可更改)。我们不能添加、更改或删除元组的项。

如果我们尝试修改元组,就会得到一个错误。例如:

cars = ('BMW', 'Tesla', 'Ford', 'Toyota')

# trying to modify a tuple
cars[0] = 'Nissan'    # error
       
print(cars)

Python 元组长度

我们使用 len() 函数来查找元组中存在的项数。例如:

cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
print('Total Items:', len(cars)) 
       
# Output: Total Items: 4

遍历元组

我们使用 for 循环遍历元组的项。例如:

fruits = ('apple','banana','orange')

# iterate through the tuple
for fruit in fruits:
    print(fruit)

输出

apple
banana
orange 

更多关于 Python 元组

检查元组中是否存在项

我们使用 in 关键字检查元组中是否存在项。例如:

colors = ('red', 'orange', 'blue')

print('yellow' in colors)    # False
print('red' in colors)       # True

这里,

  • yellow 不在 colors 中,因此 'yellow' in colors 求值为 False
  • redcolors 中,因此 'red' in colors 求值为 True
更改元组项

Python 元组是不可变的 - 一旦创建,我们就无法更改元组的项。

如果尝试这样做,就会得到一个错误。例如:

fruits = ('apple', 'cherry', 'orange')

# trying to change the second item to 'banana' fruits[1] = 'banana'
print(fruits) # Output: TypeError: 'tuple' object does not support item assignment
删除元组

我们不能删除元组的单个项。但是,我们可以使用 del 语句删除元组本身。例如:

animals = ('dog', 'cat', 'rat')

# deleting the tuple
del animals

在这里,我们删除了 animals 元组。

创建一个只包含一个项的 Python 元组

当我们想创建一个只包含一个项的元组时,我们可能会这样做

var = ('Hello')
print(var)  # string

但这不会创建一个元组;相反,它会被视为一个 字符串

要解决这个问题,我们需要在项后面加上一个逗号。例如:

var = ('Hello',) 
print(var)  # tuple

# Output: ('Hello',)

另请阅读

在我们结束之前,让我们测试一下你对 Python 元组的知识!你能解决以下挑战吗?

挑战

编写一个函数,通过在元组末尾添加一个元素来修改元组。

  • 对于元组 (1, 2, 3) 和元素 4 的输入,返回值应为 (1, 2, 3, 4)
  • 提示: 您需要首先将元组转换为另一种数据类型,例如列表。

视频:Python 列表和元组

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战