16. Python的元组(Tuple)

《Python编程的术与道:Python语言入门》视频课程
《Python编程的术与道:Python语言入门》视频课程链接:https://edu.csdn.net/course/detail/27845

Tuples (元组)

元组可看做无法更改的列表。

列表非常动态, 可以在你追加和插入元素时增长,并且可以在删除元素时缩小。 你可以在列表中修改任何元素。 有时我们希望确保程序不可以更改列表。 这就是元组的用途。

从技术上讲,列表是mutable对象,而元组是immutable 对象。

定义元组和访问元素

可以通过在括号()中放置逗号分隔的元素序列来创建元组。

# A tuple of integers
T = (1, 2, 3)
print(T)
(1, 2, 3)
# A tuple of strings
T = ('red', 'green', 'blue')
print(T)
('red', 'green', 'blue')
# A tuple with mixed datatypes
T = (1, 'abc', 1.23, True)
print(T)
(1, 'abc', 1.23, True)
# A tuple without parentheses
T = 1, 'abc', 1.23, True
print(T)
(1, 'abc', 1.23, True)

包含零个元素的元组称为空元组,可以括号()创建一个空元组

# An empty tuple
T = ()
print(T)
()

单例元组 (Singleton Tuple)

如果在一个元组中只有一个值,则可以通过在右括号前加上一个逗号来表明这一点。

#Example: Create a single item tuple

T = (4,)
print(T)
print(type(T))  # <type 'tuple'>
(4,)
<class 'tuple'>

否则,Python会认为你只是在常规括号内输入了一个值。

#Example: Not a tuple

T = (4)
print(T)
print(type(T))  # <type 'int'>
4
<class 'int'>

tuple() 构造函数

可以使用Python的tuple()构造函数将其他数据类型转换为元组。

#Example: Convert a list to a tuple
T = tuple([1, 2, 3])
print(T)    # (1, 2, 3)
(1, 2, 3)
#Example: Convert a string to a tuple of one-character strings
T = tuple('abc')
print(T)    # ('a', 'b', 'c')
('a', 'b', 'c')

嵌套元组

元组可以包含子元组,而子元组本身又可以包含子元组,依此类推。 这称为嵌套元组。

可以使用它们将数据安排为分层结构。

#Example: Create nested tuples

T = ('red', ('green', 'blue'), 'yellow')

元组打包与拆包 (Tuple Packing & Unpacking)

创建元组时,该元组中的元素将打包在一起成为对象。

#Example:

T = ('red', 'green', 'blue', 'cyan')
print(T)    # ('red', 'green', 'blue', 'cyan')
('red', 'green', 'blue', 'cyan')

在上面的示例中,值red’, ‘green’, ‘blue’ 和 ‘cyan’打包在一个元组中。
在这里插入图片描述

元组拆包

将一个打包的元组赋值给一个新的元组时,单个元素将被拆包(被赋值于新元组的元素)。

元组在 Python 里扮演了两个角色,它既可以用作无名称的字段的记录,又可以看作不可变的列表。当元组被当作记录来用的时候,拆包是最安全可靠地从元组里提取不同字段信息的方式。

#Example:

T = ('red', 'green', 'blue', 'cyan')
(a, b, c, d) = T
print(a)    # red
print(b)    # green
print(c)    # blue
print(d)    # cyan
red
green
blue
cyan
T = ('red', 'green', 'blue', 'cyan')
a, b, c, d = T
print(a)    # red
print(b)    # green
print(c)    # blue
print(d)    # cyan
red
green
blue
cyan

在上面的示例中,元组T被拆包为a,b,c和d变量。
在这里插入图片描述

拆包时,左侧的变量数必须与元组中的元素数一致。

示例:元组拆包中的常见错误

# ValueError: too many values to unpack
T = ('red', 'green', 'blue', 'cyan')
(a, b) = T
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-14-bb78d52fded9> in <module>
      1 # ValueError: too many values to unpack
      2 T = ('red', 'green', 'blue', 'cyan')
----> 3 (a, b) = T


ValueError: too many values to unpack (expected 2)
# ValueError: need more than 3 values to unpack
T = ('red', 'green', 'blue')
(a, b, c, d) = T
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-15-84dea75b55f6> in <module>
      1 # ValueError: need more than 3 values to unpack
      2 T = ('red', 'green', 'blue')
----> 3 (a, b, c, d) = T


ValueError: not enough values to unpack (expected 4, got 3)

用法

当要交换两个变量的值而不使用临时变量时,使用元组拆包非常方便。

#Example: Swap values of ‘a’ and ‘b’
a = 1
b = 99
a, b = b, a
print(a)    # 99
print(b)    # 1
99
1

一个元组的拆包时,右侧可以是任何序列(元组、字符串或列表)。

#Example: Split an email address into a user name and a domain

addr = 'bob@python.org'
user, domain = addr.split('@')

print(user)     # bob
print(domain)   # python.org
bob
python.org

访问元组元素

可以使用方括号中的索引访问元组中的单个元素。

请注意,元组索引从0开始。

元组中元素的索引如下所示:
在这里插入图片描述

#Example: Access 1st and 3rd items by positive index

T = ('red', 'green', 'blue', 'yellow', 'black')
print(T[0])     # red
print(T[2])     # blue
red
blue

也可以通过负索引访问元组。

负索引从元组的末尾开始倒计数。 因此,T[-1]是指最后一项,T[-2]是倒数第二项,依此类推。

#Example: Access last and 2nd last items by negative index

T = ('red', 'green', 'blue', 'yellow', 'black')
print(T[-1])     # black
print(T[-2])     # yellow
black
yellow

元组切片 (Tuple Slicing)

要访问元组中的一系列元素, 需要使用切片运算符对元组进行切片。

元组切片类似于列表切片。

T = ('a', 'b', 'c', 'd', 'e', 'f')

print(T[2:5]) # ('c', 'd', 'e')
print(T[0:2]) # ('a', 'b')
print(T[3:-1]) # ('d', 'e')
('c', 'd', 'e')
('a', 'b')
('d', 'e')

更改元组元素

元组是不可变的(不可更改)。 创建元组后,将无法对其进行修改。

#Example: Tuples cannot be modofied

# TypeError: 'tuple' object does not support item assignment
T = ('red', 'green', 'blue')
T[0] = 'black'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-21-d1b6b928d759> in <module>
      3 # TypeError: 'tuple' object does not support item assignment
      4 T = ('red', 'green', 'blue')
----> 5 T[0] = 'black'


TypeError: 'tuple' object does not support item assignment

元组不变性仅适用于元组本身的顶层,不适用于其内容。

例如,可以照常更改元组内的列表。

#Example: Mutable item inside a tuple can be changed

# Modifying list inside tuple
T = (1, [2, 3], 4)
T[1][0] = 'xx'
print(T)    # (1, ['xx', 3], 4)
(1, ['xx', 3], 4)

元组的相对不可变性:元组与多数 Python容器(列表、字典、集合等)一样,保存的是对象的引用。 如果引用的元素是可变的,即便元组本身不可变,元素依然可变。也就是说,元组的不可变性其实是指 tuple 数据结构的物理内容(即保存的引用)不可变,与引用的对象无关。
元组的值会随着引用的可变对象的变化而变。元组中不可变的是元素的标识。( What can never change in a tuple is the identity of the items it contains.)

删除元组

元组无法修改,因此显然无法从中删除任何元素。

但是,可以使用del关键字完全删除该元组。

#Example: Delete a tuple completely with del keyword

T = ('red', 'green', 'blue')
print(T)
del T
print(T)
('red', 'green', 'blue')



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-23-f0690e822aae> in <module>
      4 print(T)
      5 del T
----> 6 print(T)


NameError: name 'T' is not defined

元组的拼接和重复 (Tuple Concatenation & Repetition)

可以使用拼接运算符+或重复运算符*来合并连接元组

(Tuples can be joined using the concatenation operator + or Replication operator *)

#Example: Join tuples

# Concatenate
T = ('red', 'green', 'blue') + (1, 2, 3)
print(T)    # ('red', 'green', 'blue', 1, 2, 3)
('red', 'green', 'blue', 1, 2, 3)
# Replicate
T = ('red',) * 3
print(T)    # ('red', 'red', 'red')
('red', 'red', 'red')

得到元组长度

要查找元组有多少元素,可使用len()方法。

#Example: Find length of a tuple

T = ('red', 'green', 'blue')
print(len(T))   # 3
3

检查元素是否存在于元组中

要确定一个值是否在元组中,可以在if语句中使用in或not in。

#Example: Check if item exists in a tuple

# Check for presence
T = ('red', 'green', 'blue')
if 'red' in T:
    print('yes')
# Check for absence
T = ('red', 'green', 'blue')
if 'yellow' not in T:
    print('yes')
yes
yes

遍历元组

要遍历元组的元素,可使用for循环。

#Example: Print each item in a tuple

T = ('red', 'green', 'blue')
for item in T:
    print(item)    # red green blue
red
green
blue

元组排序

有两种方法可以对元组进行排序。

方法1:将元组转换为可变对象(如列表)(使用列表构造函数),获得对排序方法调用sort()的访问权,并将其转换回元组。

#Example: Sort a tuple by converting it to a list

T = ('cc', 'aa', 'dd', 'bb')
tmp = list(T) # convert tuple to list
tmp.sort()   # sort list
T = tuple(tmp) # convert list to tuple
print(T)    # ('aa', 'bb', 'cc', 'dd')
('aa', 'bb', 'cc', 'dd')

方法2:使用接受任何序列对象的内置sorted()方法。

# Example: Sort a tuple using built-in sorted() method

T = ('cc', 'aa', 'dd', 'bb')
print(tuple(sorted(T)))  # ('aa', 'bb', 'cc', 'dd')
('aa', 'bb', 'cc', 'dd')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bai666ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值