零基础入门学习Python(7):元组
2015-12-11 19:00
483 查看
零基础入门学习Python(7):元组
上一节介绍了列表,这里先补充常用的两个函数和一些基本操作reverse() :将整个列表原地翻转
sort() :用指定方式对列表排序
[code]>>> list1 = [3,2,9,17,12] >>> list1.reverse() >>> list1 [12, 17, 9, 2, 3] >>> list1.sort() #reverse默认=False,从小到大 >>> list1 [2, 3, 9, 12, 17] >>> list1.sort(reverse = True) >>> list1 [17, 12, 9, 3, 2] >>> 9 in list1 #检测 9 是否在列表中 True >>> 7 not in list1 True >>> list2 = [12] >>> list3 = [23] >>> list4 = list2 + list3 #列表拼接 >>> list4 [12, 23] >>> list4 *= 3 #列表重复 >>> list4 [12, 23, 12, 23, 12, 23]
下面介绍元组,元组(tuple)元素不可修改,访问元组元素也是通过下标
创建和访问一个元组,逗号是关键
[code]>>> temp = [] #获取变量类型 >>> type(temp) <class 'list'> >>> temp = () #空元组 >>> type(temp) <class 'tuple'> >>> temp = (1) >>> temp 1 >>> type(temp) #只有括号不是元组 <class 'int'> >>> temp = (1,) #必须有逗号才是元组 >>> type(temp) <class 'tuple'> >>> temp = 1, #没有括号有逗号也是元组 >>> type(temp) <class 'tuple'> >>> temp = (2,3,4) #访问元组元素 >>> temp[1] 3
更新和删除一个元组,不能直接通过下标,要使用分片
[code]>>> temp = (2,3,4) >>> temp = temp[:2] + ("Hello",) #记得加上逗号,否则会出错 >>> temp (2, 3, 'Hello')
元组相关的操作符:拼接操作符(+)、重复操作符(*)、关系操作符(>,>=,<,<=)、成员操作符(in, not in)、逻辑操作符(and, or,not)
[code]>>> temp1 = (1,2) >>> temp2 = (2,3,4) >>> temp3 = temp1 + temp2 >>> temp3 (1, 2, 2, 3, 4) >>> 8 * (8) #两个数相乘 64 >>> 8 * (8,) #元组的重复 (8, 8, 8, 8, 8, 8, 8, 8) >>> temp1 > temp2 False >>> 3 in temp3 True >>> 3 not in temp3 False >>> temp1 <= temp2 and temp1 <=temp3 True
零基础入门学习Python(6):列表(续)
相关文章推荐
- python安装以及配置Numpy和Scipy模块
- python学习---列表
- 第二个UI脚本--Python+selenium之unittest+HTMLtestRunner及python的继承
- 深入源码解析Python中的对象与类型
- python对象类型
- python 写三级菜单
- python 读取文件指定某行
- Python中web.py运行后窗口显示中文
- Python多线程学习
- [Python]ctypes+struct实现类c的结构化数据串行处理
- Python模板库Mako的用法
- Python函数练习:冒泡算法+快速排序(二分法)
- Python中web.py session使用,解决EOFError
- Python实现各种排序算法的代码示例总结
- python小记--lambda 装饰器 max(min)的key回调函数 sorted
- python property的用法
- python全局可变变量的坑
- 第一个UI脚本--python+selenium
- Python模板库Mako的语法
- python异常处理