摘要:本文主要向大家介绍了Python语言学习笔记(三)之元组,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
本文主要向大家介绍了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'))
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号