未加星标

元组tuple

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

tuple和list的主要区别就是tuple里的元素的是不能改变的,即tuple时immutable的

#创建tuple >>> tupa = (12 , 'ed' , 34) >>> tupb = 134 , 'hf', 43 >>> tupc = (12 ,) #一个元素的时候不能不写"," >>> print tupa,tupb, tupc (12, 'ed', 34) (134, 'hf', 43) (12,) #访问tuple #tupb[1:2]包括第1个但不包括第2个,python很多地方都是这样的 >>> print tupa[0],tupb[1:2], tupc[-1] , tupb[-2] 12 ('hf',) 12 hf #更新tuple #tuple是immutable的,里面的值不能更改 >>> tupa[0] = 10 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment #合并tuple >>> tupd = tupa + tupb >>> print tupa, tupb, tupd (12, 'ed', 34) (134, 'hf', 43) (12, 'ed', 34, 134, 'hf', 43) #删除tuple #tuple是immutable的,里面的值不能删除,只能使用del删除整个tuple >>> del tupd[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion >>> del tupd >>> print tupd Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'tupd' is not defined 基本操作 #测试tuple里元素的数目 >>> len(tupa) 3 #合并tuple >>> print tupa+tupb (12, 'ed', 34, 134, 'hf', 43) #重复tuple >>> print tupa*2, tupa[0]*3, tupa[1]*4 (12, 'ed', 34, 12, 'ed', 34) 36 edededed #元素所属 >>> 12 in tupa True >>> 12 in tupa, 14 in tupa (True, False) >>> test = 12 in tupa >>> print test True >>> test = 12 in tupa, 15 in tupa >>> print test (True, False) #遍历元素 >>> for x in tupa: ... print x ... 12 ed 34 Built-in Tuple Functions cmp()

Compares elements of both tuples.If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers.

If numbers, perform numeric coercion if necessary and compare. If either element is a number, then the other element is "larger" (numbers are "smallest"). Otherwise, types are sorted alphabetically by name.

If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both tuples and share the same data, the result is a tie, meaning that 0 is returned

Syntax&P cmp(tuple1, tuple2) eg >>> cmp (tupa,tupb) -1 len()

Returns the total length of the tuple.

Syntax&P len(tuple) eg >>> len(tupa) 3 max()

Returns item from the tuple with max value.

Syntax&P max(tuple) eg >>> max(tupa) 'ed' min()

Returns item from the tuple with min value.

Syntax&P min(tuple) eg >>> min(tupa) 12 tuple()

Converts a list into tuple

Syntax&P tuple(seq) eg >>> lia=[12,14,'12'] >>> print tuple(lia) (12, 14, '12')

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: 删除Python
分页:12
转载请注明
本文标题:元组tuple
本站链接:http://www.codesec.net/view/479662.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(44)