继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python学习笔记(三)之元组

12345678_0001
关注TA
已关注
手记 64
粉丝 12
获赞 46

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'))

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP