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




     本文转自品鉴初心51CTO博客,原文链接:

http://blog.51cto.com/wutengfei/2057005

,如需转载请自行联系原作者




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值