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

tuple

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

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

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 进行访问。github

排序

须要注意的是,之因此说 tuple 是有序的,指的是 tuple item 是按照顺序定义的,而且这个顺序是不可更改的。markdown

不可修改

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

容许重复

由于 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() 函数,以下代码所示:this

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,以下代码所示:code

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/pyt...

更多高质量干货:参见个人 GitHub: python

相关文章
相关标签/搜索