首页 > 编程语言 > 详细

Python:list用法

时间:2016-06-02 19:44:36      阅读:186      评论:0      收藏:0      [点我收藏+]

list是一种有序的集合,可以随时添加和删除其中的元素。

定义

空list

>>> a_list=[]
>>> a_list
[]

普通

>>> a_list=[1,2,3,4,5]
>>> a_list
[1, 2, 3, 4, 5]

遍历

>>> for i in a_list:
...     print i
... 
1
2
3
4
5

添加

append:末尾增加元素,每次只能添加一个

>>> a_list.append(‘adele‘)
>>> a_list
[1, 2, 3, 4, 5, ‘adele‘]

insert:在任意位置插入

>>> a_list.insert(1,‘taylor‘)
>>> a_list
[1, ‘taylor‘, 2, 3, 4, 5, ‘adele‘]

extend:末尾增加,另一个list的全部值

>>> a_list.extend([‘1989‘,‘hello‘])
>>> a_list
[1, ‘taylor‘, 2, 3, 4, 5, ‘adele‘, ‘1989‘, ‘hello‘]

删除

pop:删除最后/指定位置元素,一次只能删一个

>>> a_list.pop()    #默认删除最后一个值
‘hello‘  

>>> a_list.pop(1) #指定删除位置 ‘taylor‘

remove:移除列表某个值的第一个匹配项

>>> a_list
[1, 1, 2, 3, 4, 5, ‘1989‘, ‘adele‘]
>>> a_list.remove(1)
>>> a_list
[1, 2, 3, 4, 5, ‘1989‘, ‘adele‘]

del:删除一个或连续几个元素

>>> del a_list[0]    #删除指定元素
>>> a_list
[2, 3, 4, 5, ‘1989‘, ‘adele‘]

>>> del a_list[0:2] #删除连续几个元素 >>> a_list [4, 5, ‘1989‘, ‘adele‘]
>>> del a_list #删除整个list >>> a_list Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘a_list‘ is not defined

排序和反序

排序

>>> a_list.sort()
>>> a_list
[1, 1, 2, 3, 4, 5, ‘1989‘, ‘adele‘]

反序

>>> a_list
[1, 2, 3, 4, 5, ‘1989‘, ‘adele‘]
>>> a_list.reverse()
>>> a_list
[‘adele‘, ‘1989‘, 5, 4, 3, 2, 1]

几个操作符

>>> [1,2,3]+[‘a‘,‘b‘,‘c‘]
[1, 2, 3, ‘a‘, ‘b‘, ‘c‘]

>>> [‘hello‘]*4 [‘hello‘, ‘hello‘, ‘hello‘, ‘hello‘]
>>> 1 in [1,2,3] True

 

Python:list用法

原文:http://www.cnblogs.com/lilip/p/5554068.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!