python元组、列表的异同总结
2015-06-25 10:04
573 查看
定义的异同:
列表(list):
list是一种有序的集合,可以随时添加和删除其中的元素,用 [] 表示。列表的三个特性:①创建之后也可以加减修改元素; ②元素可以是数字、字符、变量等,也可以混杂; ③列表可以嵌套。
例如:
>>>f=3 >>>list_example = [1, 'dog', f, ['monkey', 'duck']] >>>list_example [1, 'dog', 3, ['monkey', 'duck']]
元组(tuple):
tuple也是有序的集合,它和list不同的是它只能在初始化的时候赋值,之后就不能再进行添加删除元素了,用 () 表示。元组的三个特性:①创建之后不能加减修改元素; ②元素也可以是数字、字符、变量或者混杂; ③元组也可以嵌套。
例如:
>>>f=3 >>>tuple_example = (1, 'dog', f, ('monkey', 'duck')) >>>tuple_example (1, 'dog', 3, ('monkey', 'duck'))
综上可以看出,tuple和list的不同主要在于: tuple在初始化之后不能再修改,但是list可以。
各种相同:
两者除了在初始化后能否再变化这个问题上不相同外,其他方面几乎都是相同的。初始化:
list_example = [1, 2, [3, 4], 5, 6]
tuple_example = (7, 8, (9, 10), 11, 12)
用法上的相同点:
1、如果只有一个元素,要在后面加个’,’,否则只相当于定义了一个变量:>>>list_example = [1] 1 >>>list_example = [1,] [1] >>>tuple_example = (1,) (1,)
2、利用索引输出元素(注意索引从0开始):
>>>list_example[0] 1 >>>tuple_example[2][0] 9
3、索引为负数,表示从尾往前搜索(-1表示最后一个元素):
>>>list_example[-1] 6 >>>tuple_example[-3][-1] 10
4、tuple和list可以相互嵌套:
>>>list_example = [1,(2,3)] [1,(2,3)] >>>tuple_example = (4,[5,6]) >(4,[5,6])
方法上的相同点:
1、:返回元素中elem的个数>>>tuple_example = (7, 8, (7, 10), 7, 12) >>>tuple_example.count(7) 2
2、:返回元素elem的索引
>>>list_example = [7, 8, (7, 10), 8, 12] >>>list_example.index(8) 1
各种不同:
因为tuple不能修改删除,而已list可以,所以有些方法是list才有的。初始化:
list_example = [1, 2, [3, 4], 5, 6]
1、:在末尾添加元素:
>>>list_example.append(100) [1, 2, [3, 4], 5, 6, 100] >>>list_example.append([100, 200]) [1, 2, [3, 4], 5, 6, 100, [100, 200]]
2、:在末尾添加元素,但object必须是列表,object的元素将会添加到列表的末尾:
>>>list_example.append([100, 200]) [1, 2, [3, 4], 5, 6, 100, 200]
3、:将元素object添加到索引为index的位置:
>>>list_example.insert(1, 'abc') [1, 'abc', 2, [3, 4], 5, 6]
4、:将索引为index的元素弹出列表:
>>>list_example.pop(1) 2 >>>list_example [1, [3, 4], 5, 6]
5、:删除元素value(只删除第一个出现的)
>>>list_example = [1, 2, 5, [3, 4], 5, 6] >>>list_example.remove(5) >>>list_example [1, 2, [3, 4], 5, 6]
6、:对元素排序。
默认是从小到大,不同类型的元素按数字—>列表—>字符—>元组先后排序。
>>>list_example = [1, 'cd', ('b', 'f'), 8, 'ab', [4, 3], (1, 2), [2,9], 5, 6] >>>list_example.sort(cmp=None, key=None, reverse=False) >>>list_example [1, 5, 6, 8, [2, 9], [4, 3], 'ab', 'cd', (1, 2), ('b', 'f')]
总之,tuple和list功能上是很相近的,只是tuple在初始化后就不能更改了,这也说明tuple具有更高的安全性,防止数据被误修改。对于无需修改的数据,类似于“只读”性质的数据,最好选用tuple。
转载请注明出处,谢谢!(原文链接:http://blog.csdn.net/bone_ace/article/details/46633029)
相关文章推荐
- python元组、列表的异同总结
- Python 3 + Sulime Text 2 输出中文出错
- python自定义包使用
- python 去除 list 重复元素
- Python标准库3.4.3-webbrowser-21.1
- Python解析HDF文件
- Python解析HDF文件
- Python解析HDF文件 分类: Python 2015-06-25 00:16 743人阅读 评论(0) 收藏
- Python安装模块出现问题UnicodeDecodeError的解决方法
- Python中的zipfile模块使用详解
- Python 的datetime转成总毫秒数
- python socket之udp说明
- python 远程执行命令、发布文件
- python 分布式进程体验
- python 日期时间处理
- python 压缩每周生成的数据文件
- python常用函数库及模块巧妙用法汇总
- python Multiprocessing 多进程应用
- Python输出字符串或文件颜色显示
- 免密码登录服务器python脚本