元组/数组 tuple
Python 有两种序列结构,分别是元组 ( tuple ) 和串列 ( list ),两种序列都可以将任何一种对象作为它们的元素,这篇教学将会介绍 tuple 的用法与限制 ( tuple 的发音可以念成 too-pull 也可念成 tub-pull,中文称为元组或数组 )。
快速导览:tuple 与串列 list 的差异、使用 tuple 的好处、建立 tuple、读取 tuple 的内容、使用 + 号结合 tuple、使用*号重复项目、强制修改 tuple
本篇使用的 Python 版本为 3.7.12,所有范例可使用 Google Colab 实作,不用安装任何软件 ( 参考:使用 Google Colab )
tuple 与串列 list 的差异
tuple 和串列非常的类似,都是一个储存数据的“容器”,可以将对象存入,变成有顺序的序列结构,不过 tuple 和串列有以下几点不同:
- tuple“只要建立了,就不能修改内容”。
- tuple 使用“小括号”,串列 list 使用“方括号”。
- 如果 tuple 里只有一个元素,后方必须加上“逗号”( 多个元素就不用 )。
使用 tuple 的好处
虽然 tuple 在使用上有不少限制,但 tuple 也是有一些好处:
- 读取速度比串列快。
- 占用的空间比较少。
- 数据更安全 ( 因为无法修改 )。
建立 tuple
建立 tuple 有两种方法:“使用小括号和逗号”和“使用 tuple()”。
使用小括号和逗号
透过小括号包覆内容,用逗号将内容隔开,就可以建立一个基本的 tuple,下方的例子,可以看到 a 和 b 的型别都是 tuple ( 注意,因为 b 只有一个元素,所以元素后方要加上逗号 )。
a = ('apple','banana','orange','grap') b = ('apple',) type(a) # tuple type(b) # tuple使用 tuple()
使用“
tuple(串列)”可以将串列转换成 tuple。a = ['apple','banana','orange','grap'] b = tuple(a) type(b) # tuple
读取 tuple 的内容
读取 tuple 的内容有两种方法:“使用变数”、“索引值 offset”。
使用变数
因为 tuple 可以一次赋予多个变数内容,透过这个方法可以一次将项目丢给不同的变数,接着只要读取变数,就能读取对应内容 ( 注意,使用这个方法时,变数的数量要等于 tuple 的内容数量 )。
t = ('apple','banana','orange','grap') a, b, c, d = t print(a) # apple print(b) # banana print(c) # orange print(d) # grap索引值 offset
在 tuple 里每个项目都有自己的索引值 offset,指定 offset 就能读取该数据的内容。
t = ('apple','banana','orange','grap') print(t[0]) # apple print(t[1]) # banana print(t[2]) # orange print(t[3]) # grap
使用 + 号结合 tuple
类似字串的结合方式,使用 + 号,可以将不同的 tuple 合并。
t1 = ('apple','banana','orange')
t2 = ('grap','pineapple')
t = t1 + t2
print(t) # ('apple', 'banana', 'orange', 'grap', 'pineapple')
使用*号重复项目
使用*号,可以将重复一个 tuple 内的所有项目,并产生一个新的 tuple。
a = ('apple','banana','orange')
b = a*3
print(b) # ('apple', 'banana', 'orange', 'apple', 'banana', 'orange', 'apple', 'banana', 'orange')
强制修改 tuple
使用串列 list 存取 tuple 数据,修改数据后,再转换为新的 tuple ( 注意,虽然变数名称相同,但两个 tuple 是完全不同的 )。
a = ('apple','banana','orange')
b = list(a)
b.append('grap')
a = tuple(b)
print(a) # ('apple', 'banana', 'orange', 'grap')
微信扫码关注
抖音扫码关注