python 内置数据结构tuple

  • 元组简介

元组有序元素组成的对象,元组是只读的不可变的数据类型(对象),可hash,不能进行添加、删除、修改的操作

  • 定义元组的三种方式

第一种 使用内置函数tuple()函数

In [19]: t=tuple()

In [20]: type(t)
Out[20]: tuple

  

第二种 使用()直接定义 

In [23]: t=(1,2)

In [24]: type(t)
Out[24]: tuple

  

注意当只有一个元素时,需要在元素后面加逗号 否则会被认为是其他类型对象

In [25]: t=(1)

In [26]: type(t)
Out[26]: int

In [27]: t=('1')

In [28]: type(t)
Out[28]: str

In [29]: t=('1',)

In [30]: type(t)
Out[30]: tuple

  

第三种 使用tuple()函数初始化一个可迭代对象

In [31]: t=tuple(range(10))

In [32]: t
Out[32]: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

In [33]: type(t)
Out[33]: tuple

In [37]: t=tuple([1,2,4,5])

In [38]: t
Out[38]: (1, 2, 4, 5)

In [39]: type(t)
Out[39]: tuple

  

  • 索引访问:元组和列表一样是可索引,有边界超出索引边界后会抛出异常 “IndexError”,可倒序访问-1

In [41]: t
Out[41]: (1, 2, 4, 5)

In [42]: t[1]
Out[42]: 2

In [43]: t[-1]
Out[43]: 5

In [44]: t[-100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-44-dfa1185694f1> in <module>()
----> 1 t[-100]

IndexError: tuple index out of range

In [45]: t[10]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-45-c7de5e7e0c13> in <module>()
----> 1 t[10]

IndexError: tuple index out of range

  

 

 

 

 

  • index:查找Value对应的索引,有多个相同值时仅返回找到的第一个值的索引,可以定义查找的起始和结束位置,当值不存在时会抛出错误"ValueError"

In [54]: t=(1,2,4,2,6,4,8)

In [55]: t
Out[55]: (1, 2, 4, 2, 6, 4, 8)
#默认从0开始查找
In [56]: t.index(2)
Out[56]: 1
#定义起始查找位置
In [57]: t.index(2,3)
Out[57]: 3

In [58]: t.index(4,3)
Out[58]: 5
#定义开始和结束位置
In [59]: t.index(4,3,8)
Out[59]: 5
#结束索引超出边界时,结束索引默认等于其长度减一,so 不会抛出错误
In [60]: t.index(4,3,100)
Out[60]: 5

  

 count:和列表一样统计Value在元组中的次数

In [62]: t
Out[62]: (1, 2, 4, 2, 6, 4, 8)

In [63]: t.count(2)
Out[63]: 2

In [64]: t.count(1)
Out[64]: 1

In [65]: t.count(0)
Out[65]: 0

  

 

posted @ 2018-04-09 10:14  mictiger  阅读(159)  评论(0)    收藏  举报