Python 入门系列 —— 17. tuple 简介

tuple

tuple 常用来将多个 item 放在一个变量中,同时tuple也是python 4个集合类型之一,其他的三个是:List,Set,Dictionary,它们都有自己的用途和场景。

tuple 是一个有序但不可更改的集合,用 () 来表示,如下代码所示:


thistuple = ("apple", "banana", "cherry")
print(thistuple)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
('apple', 'banana', 'cherry')

tuple 项

tuple中的项是有序的,不可更改的,并且可以重复的值,同时tuple中的项也是索引过的,也就是说你可以使用类似 [0][1] 的方式对 tuple 进行访问。

排序

需要注意的是,之所以说 tuple 是有序的,指的是 tuple item 是按照顺序定义的,并且这个顺序是不可更改的。

不可修改

所谓 tuple 不可修改,指的是不可对 tuple 中的item 进行变更。

允许重复

因为 tuple 是索引化的,意味着不同的索引可以具有相同的值,比如下面的代码。


thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
('apple', 'banana', 'cherry', 'apple', 'cherry')

Tuple 长度

要想知道 tuple 中有多少项,可以使用 len() 函数,如下代码所示:


thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
3

创建单值的 tuple

要想创建一个单值 tuple,需要在 item 之后添加 , ,否则 python 不会认为这个单值的集合为 tuple,如下代码所示:


thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
<class 'tuple'>
<class 'str'>

Tuple 中的数据类型

tuple中的项可以是任意类型,比如说:string,int,boolean 等等,如下代码所示:


tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

又或者 tuple 中的 item 是混杂的,比如下面这样。


tuple1 = ("abc", 34, True, 40, "male")

type()

从 python 的视角来看,tuples 就是一个 tuple class 类,如下代码所示:


mytuple = ("apple", "banana", "cherry")
print(type(mytuple))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
<class 'tuple'>

tuple() 构造函数

尽可能的使用 tuple() 构造函数来生成一个 tuple。


thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
('apple', 'banana', 'cherry')

译文链接:https://www.w3schools.com/python/python_tuples.asp

更多高质量干货:参见我的 GitHub: python

猜你喜欢

转载自blog.csdn.net/huangxinchen520/article/details/112261594