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

Python:list用法

2016-06-02 18:38 429 查看

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]

  等价语句

#此语句不能从根本上反序,而是暂时生成一个新的值
>>> a_list=[1,2,3] >>> a_list [1, 2, 3] >>> a_list[::-1] [3, 2, 1] >>> a_list [1, 2, 3]

几个操作符

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

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

 

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