手记

python学习笔记(三)之元组

python学习笔记(三)之元组
说明:元组是python中的一种对象类型。它与之前的列表、字符串、整数、浮点数等并列。跟列表很接近。
实例1:

>> t = 123,'abc',["come,here"]
>> t
(123, 'abc', ['come,here']) ##tuple(元组)
>> type(t)
<type 'tuple'>
说明:元组都是用圆括号括起来的,其中的元素之间用逗号隔开。
元组中的元素类型是任意的python对象(数据)跟列表相同。
元组中的数据不能更改,这点与列表不同。
实例2:
>> t = 123,'abc',["come,here"],("python","learn")
>> t
(123, 'abc', ['come,here'], ('python', 'learn'))
>> t[0] = 8 ##不能原地修改
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>> t.append("no") ##不能原地增加
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

索引与切片
实例3:

>> t = 123,'abc',["come,here"],("python","learn")
>> t
(123, 'abc', ['come,here'], ('python', 'learn'))
>> t[2]
['come,here']
>> t[2:]
(['come,here'], ('python', 'learn'))
>> t[2][0]
'come,here'
>> t[1][0]
'a'

特别说明:
如果一个元组中只有一个元素的时候,应该在该元素后面加一个半角的英文逗号。
实例4:

>> a = (3)
>> type(a)
<type 'int'>
>> b = (4,)
>> type(b)
<type 'tuple'>

分别用list()与tuple()进行两者的转换:
实例5:

>> t
(123, 'abc', ['come,here'], ('python', 'learn'))
>> tls = list(t) ##tuople --> list
>> tls
[123, 'abc', ['come,here'], ('python', 'learn')]
>> t_tuple = tuple(tls)  ##list --> tuple
>> t_tuple
(123, 'abc', ['come,here'], ('python', 'learn'))

0人推荐
随时随地看视频
慕课网APP