Python入门教程--元组
来源:互联网 发布:易哲软件 编辑:程序博客网 时间:2024/05/20 20:21
一、语法
(elem1,elem2...)
元组与列表类似,不同之处在于
1).元组的元素不能修改。
2).元组使用小括号,而列表使用方括号。
可以创建一个空的元组
tup=()
注意:元组中只包含一个元素时,需要在元素后面添加逗号。
tup=(50,)
>>> print ('hi')*4hihihihi>>> print ('hi',)*4('hi', 'hi', 'hi', 'hi')>>>
>>> tup1=(23)>>> print tup123>>> type(tup1)<type 'int'>>>> tup2=(23,)>>> print tup2(23,)>>> type(tup2)<type 'tuple'>>>>
二、操作元组
1.访问元组
可以使用下标索引来访问元组中的值。下标索引从0开始。
>>> tup1=('a','b','c','d')>>> print "tup1[1]:",tup1[1]tup1[1]: b>>>
>>> tup1=('a','b','c','d')>>> print tup1[-2]c>>> print tup1[1:]('b', 'c', 'd')>>>2.修改元组
元组中的元素值是不允许修改的,但是可以对元组进行连接组合。
>>> tup1=('a','b','c','d')>>> print "tup1[1]:",tup1[1]tup1[1]: b>>> tup1[2]='e'Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> tup1[2]='e'TypeError: 'tuple' object does not support item assignment>>> tup2=('e','f','g')>>> print tup1+tup2('a', 'b', 'c', 'd', 'e', 'f', 'g')>>>3.删除元组
可以使用del语句删除整改元组。
>>> del tup2>>> print tup2Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> print tup2NameError: name 'tup2' is not defined>>>三、元组运算符表达式结果描述len((1,2,3))3计算元素个数(1,2.3)+(4,5,6)(1,2,3,4,5,6)连接('hi',)*4('hi','hi','hi','hi')复制3 in (1,2,3)True元素是否存在for x in (1,2,3:print x,1 2 3迭代
四、元组内置函数
cmp():比较两个元组元素
如果比较的元素是同类型的,则比较其值,返回结果。
如果两个元素不是同一种类型,则检查它们是否是数字。
- 如果是数字,执行必要的数字强制类型转换,然后比较。
- 如果有一方的元素是数字,则另一方的元素"大"(数字是"最小的")
- 否则,通过类型名字的字母顺序进行比较。
如果有一个列表首先到达末尾,则另一个长一点的列表"大"。
如果我们用尽了两个列表的元素而且所 有元素都是相等的,那么结果就是个平局,就是说返回一个 0。
>>> tup1=('a','b','c','d')>>> tup2=('e','f','g','h')>>> print cmp(tup1,tup2)-1>>>len():计算元组元素个数
>>> tup1=('a','b','c','d')>>> print len(tup1)4>>>max():返回元组中元素最大值
>>> tup3=('a',30,50,'e',"string")>>> print max(tup3)string>>>min():返回元组中元素最小值
>>> tup3=('a',30,50,'e',"string")>>> print min(tup3)30>>>tuple():将列表转换为元组
>>> list1=[1,2,3,4,5,6]>>> print tuple(list1)(1, 2, 3, 4, 5, 6)>>>
0 0
- Python入门教程--元组
- Python入门教程-08 元组tuple
- 2.5 python中的列表和元组 [python入门教程]
- ReportStudio入门教程(五十八) - 交集元组
- Python 元组
- Python 使用元组
- Python组元陷阱
- python元组学习
- Python:元组函数
- Python 元组 小结
- PYthon中的元组
- python学习-元组
- python 元组
- Python 元组
- python 元组
- python 元组
- Python元组类型
- Python 元组
- iOS开发笔记--CocoaPods详解_进阶篇
- 【C语言】C语言注释转换成C++注释。
- 初探 iOS8 中的 Size Class
- 完成一个一对多关系的数据输入窗口,单选删除还有问题,待改进
- 对Extjs中store的多种操作
- Python入门教程--元组
- 推酷上一些比较好的文章
- UIView 渲染和内容管理
- Hadoop之——Hive笔记
- iOS开发笔记——CocoaPods详解_制作篇
- python 装饰器
- 2015061405 - 人体各器官休息表
- Uva 232 Crossword Answers
- 14-06-2015 Java_Home and Path