python基础(三)元组tuples

一、tuple元组的定义

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。示例如下:

>>> tup1 = ('361way', 'com', 1997, 2000)
>>> type(tup1)
>>> tup2 = (1, 2, 3, 4, 5 )
>>> tup3 = "a", "b", "c", "d"
>>> type(tup3)

这里通过tup3可以看出,其并没有用小括号进行包括,但其也是元组。所以需要记住:任意无符号的对象,以逗号隔开,默认为元组 。另外需要特别注意只有一个元素时元组的创建:

>>> tup1=(111)
>>> type(tup1)
<type 'int'>
>>> tup1=("abc")
>>> type(tup1)
<type 'str'>
>>> tup1=("abc",)
>>> type(tup1)
<type 'tuple'>

元组中只包含一个元素时,需要在元素后面添加逗号,否则就会是int  或 string 等其他数据类型。如果只是创建一个空元组时,则不受逗号的影响:

>>> tup1 = ()
>>> type(tup1)

二、元组的索引与切片

同字符串、列表类型一样,元组也支持索引与切片 。而且用法也相同,下面结合示例查看下:

>>> tup1 = ('361way', 'com', 2013, 2014)
>>> tup1[0]
'361way'
>>> tup1[4]  //取值超出其索引范围时报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>> tup2[1:5]
(2, 3, 4, 5)

由上面的结果可以看出,取出元组的单个元素数据时,得到的是该数据原来的类型 ; 取出其一段元素值时得到的仍是元组。

三、修改元组的值

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

>>> tup1 = ('361way', 'com', 2013, 2014)
>>> del  tup1[3]  //删除单个元素,报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> tup1[3]='abc' //更改一个元素的值,报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> del  tup1  //删除整个元组,正常
>>> tup1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tup1' is not defined

在实际应用中,有时候会遇到需要修改元组的值,那怎么办呢?可以通过一个变通的方法实现,示例如下:

>>> tup1 = ('361way', 'com', 2013, 2014)
>>> list1 = list(tup1)
>>> list1
['361way', 'com', 2013, 2014]
>>> list1[3]='change'
>>> list1
['361way', 'com', 2013, 'change']
>>> tup1=tuple(list1)
>>> tup1
('361way', 'com', 2013, 'change')
>>>

我们可以将tuple元组的值先通过list转化为列表,再对列表内的值进行修改,修改为再将list转化为tuple 。不过这里需要注意的是此时的tup1已经非彼tup1,具体可以通过id函数进行查看,发现其内存地址已经发生了变化。

四、元组的运算符

同字符串、列表一样,元组也支持cmp、max、len、+、*、in等运算符操作或判断操作。具体如下表:

Python 表达式 结果 描述
min((1, 2, 3)) 1 计算最小值
max((1, 2, 3)) 3 计算最大值
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3,4) + (4, 5, 6,3) (1, 2, 3, 4, 4, 5, 6, 3) 连接
[‘Hi!’] * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) 复制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print x, 1 2 3 迭代

注:tuple元组同样支持enumerate 函数进行枚举,用法和列表一样,这里就不再举例 。

五、元组的内置函数

由于元组内的数据是不允许进行修改的,所以元组支持的内置函数也较少,通过help查看,主要有index和count两个

>>> help(tuple)
count(...)     T.count(value) -> integer -- return number of occurrences of value
index(...)     T.index(value, [start, [stop]]) -> integer -- return first index of value.

示例如下:

>>> tup1
('361way', 'com', 2013, 'change')
>>> tup1.count(2013)
1
>>> tup1.count(3)
>>> tup1.index(2013)
2
>>> tup1.index("com")
1

python基础(三)元组tuples》有1条评论

  1. 我也在学习Python2.x
    希望和贵站交换下连接,不知道行不,
    无论与否,我都会加上贵站的,
    因为你是我学习的榜样,以后会常来。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注