码迷,mamicode.com
首页 > 编程语言 > 详细

python基本数据类型——tuple

时间:2017-06-03 00:54:58      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:object   recent   error   support   迭代   列表   创建   trace   kernel   

一、元组的创建与转换:

ages = (11, 22, 33, 44, 55)
ages = tuple((11, 22, 33, 44, 55))
ages = tuple([]) # 字符串、列表、字典(默认是key)
  • 元组基本上可以看成不可修改的列表
  • tuple(iterable),可以存放所有可迭代的数据类型

 

二、元组的不可变性

如:t = (17, ‘Jesse‘, (‘LinuxKernel‘, ‘Python‘), [17, ‘Jesse‘])
元组t中的元素数字17和字符串‘Jesse’以及元组(‘LinuxKernel‘, ‘Python‘)本身属于不可变元素,故其在元组中不可更新;但是其中包含的列表[17, ‘Jesse‘]本身属于可变元素,故:

技术分享
>>> t = (17, ‘Jesse‘, (‘LinuxKernel‘, ‘Python‘), [17, ‘Jesse‘])
>>> t
(17, ‘Jesse‘, (‘LinuxKernel‘, ‘Python‘), [17, ‘Jesse‘])
>>> t[0] = 18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ‘tuple‘ object does not support item assignment
>>> t[3]
[17, ‘Jesse‘]
>>> t[3][0] = 21
>>> t
(17, ‘Jesse‘, (‘LinuxKernel‘, ‘Python‘), [21, ‘Jesse‘])
技术分享

 

三、元组常用操作

技术分享
#count(self,value)
#功能:统计当前元组中某元素的个数
tup = (55,77,85,55,96,99,22,55,)
tup.count(55)
#返回结果:3   元素‘55’在元组tup中出现了3次



#index(self, value, start=None, stop=None)
功能:获取元素在元组中的索引值,对于重复的元素,默认获取从左起第一个元素的索引值
tup = (55,77,85,55,96,99,22,55,)
tup.index(55)
返回结果:0
tup.index(85)
返回结果:2
tup.index(55,2,7)
返回结果:3
技术分享
技术分享 tuple源码

 

python基本数据类型——tuple

标签:object   recent   error   support   迭代   列表   创建   trace   kernel   

原文地址:http://www.cnblogs.com/yechanglv/p/6935623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!