python元组、列表的异同总结
来源:互联网 发布:网络打印app 编辑:程序博客网 时间:2024/05/01 02:07
定义的异同:
列表(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、
>>>tuple_example = (7, 8, (7, 10), 7, 12)>>>tuple_example.count(7)2
2、
>>>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、
>>>list_example.append([100, 200])[1, 2, [3, 4], 5, 6, 100, 200]
3、
>>>list_example.insert(1, 'abc')[1, 'abc', 2, [3, 4], 5, 6]
4、
>>>list_example.pop(1)2>>>list_example[1, [3, 4], 5, 6]
5、
>>>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中列表、元组、字典的异同
- python字符串,元组,列表,集合的基础总结
- Python数据结构中列表,字典,元组,集合的总结
- Python的列表和元组知识总结
- python列表和元组总结
- Python 数组[],元组(),字典{}的异同
- python--列表,元组
- python <列表 元组>
- Python列表、元组
- Python 元组 列表
- python 列表 元组
- python的元组、列表、字典
- Python的列表与元组
- python的列表和元组
- python的列表,元组,集合,字典
- Python列表和元组的使用
- python的列表 元组 字典
- 简述 IOS中的LazyLoad思想
- android 通知栏背景颜色跟随app导航栏背景颜色变化而变化
- LMAX Disruptor——一个高性能、低延迟且简单的框架
- Merge Intervals
- 浅谈MVP In Android
- python元组、列表的异同总结
- fatal error C1083: 无法打开预编译头文件:“Debug\opencv.pch”: No such file or directory
- 各种排序算法的分析及java实现
- gdb调试使用frame i命令
- Codeforces Round #309 (Div. 1) A B C
- Linux的sleep()和usleep()的使用和区别
- Servlet中初始化参数和上下文参数的配置
- 讯飞在线命令识别 动态库 交叉编译后找不到的问题
- ubuntu deepin 使用chkconfig sysv-rc-conf 命令来管理服务