您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: