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

Python学习笔记 -- 序列(三)列表

2015-05-10 08:52 344 查看

Python学习笔记 – 序列(三)列表

标签(空格分隔): python 序列 列表

列表(list),也是是Python中的数据集类型之一。如字符串一样,列表也是序列类型,因此和字符串有一些相同的特点。

列表和字符串的区别体现在下面几点:

列表可以包含其他元素,而不仅是字符。

列表是可变类型。

注意:列表的强大之处在于列表是列表时可变的,而这也是危险之处,所以使用列表时必须要小心,防止意外导致值发生改变。

>>> alist = ['a','b','c',1,2,3]
>>> print alist
['a', 'b', 'c', 1, 2, 3]
>>> id(alist)
40989200
>>> alist.append(4)
>>> print alist
['a', 'b', 'c', 1, 2, 3, 4]
>>> id(alist)
40989200
>>> alist[1]
'b'
>>> alist[1] = 'B'
>>> print alist
['a', 'B', 'c', 1, 2, 3, 4]
>>> id(alist)
40989200
>>>


列表也是序列,所以也可以通过下标来访问其中的值。当然,其也有切片操作。

>>> alist[:]
['a', 'B', 'c', '1', '2', '3']
>>> alist[2:4]
['c', '1']
>>> alist[1:]
['B', 'c', '1', '2', '3']
>>>


列表的创建

Python中的列表通过几种方式创建:


1. 通过列表的构造函数list来创建

>>> list('abcd')
['a', 'b', 'c', 'd']
>>> list([1,2,3])
[1, 2, 3]
>>> list(('a','b','c',1,2,3))
['a', 'b', 'c', 1, 2, 3]
>>> list({'a':1,'b':2})
['a', 'b']
>>>


注意,使用list()时注意传入的参数要是序列或可迭代的对象,比如:字符串、列表、元组、字典等,不是这些类型,则会报错。这里就体现了内置函数的转换作用,即将其他序列或可迭代的对象转换为列表。

>>> list(12345)

Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
list(12345)
TypeError: 'int' object is not iterable
>>>


2. 通过[]来创建 - - 字面量创建

>>> alist=[1,2,3,4]
>>> print alist
[1, 2, 3, 4]
>>> ['a','b',1,2,[3,4]]
['a', 'b', 1, 2, [3, 4]]
>>>


3. 通过range来创建整数列表


>>> alist=[1,2,3,4] >>> print alist [1, 2, 3, 4] >>> ['a','b',1,2,[3,4]] ['a', 'b', 1, 2, [3, 4]] >>>alist = range(10)
>>> print alist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> blist = range(1,8)
>>> print blist
[1, 2, 3, 4, 5, 6, 7]
>>> clist = range(1,10,2)
>>> print clist
[1, 3, 5, 7, 9]
>>>


range()是用于迭代生成一个序列的函数,可以生成等差级数。

range(…)

range(stop) -> list of integers

range(start, stop[, step]) -> list of integers

start为开始,stop为结束(不取这个值,即左闭右开),step为步长。

列表运算符操作

1. +和*运算符(重载运算符)

运算符作用
+运算符用于连接列表(只能连接列表)
*运算符用于重复列表内容
>>> alist = ['Hello']
>>> alist + 'Python'

Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
alist + 'Python'
TypeError: can only concatenate list (not "str") to list
>>> alist + ['Python']
['Hello', 'Python']
>>>
>>> alist * 2
['Hello', 'Hello']
>>>


列表操作中+运算符只能连接列表,连接其他内容会报错。

2. in和not in运算符

运算符作用
in运算符用于检查一个对象是否在列表中
not in运算符用于检查某对象是不在列表中
>>> 'Hello' in alist
True
>>> 'Python' in alist
False
>>> 'Python' not in alist
True
>>>


in和not in在列表中的用法和字符串中一样,均用于检测成员。

列表的比较

单个字符比较

>>> ['a','b','c','d'] > ['a','b','c']
True
>>> ['a','b','c','d'] = ['a','b','c']
SyntaxError: can't assign to literal
>>> [1,2,3,4] > ['a','b','c','d']
False


列表比较中,由于列表可以包含各种类型,所以比较不能想当然的认为就是true或false。需要尽量避免这样的比较。

列表的操作

1. 修改列表

通过索引

>>> aList=[1,2,3,4,5,6]
>>> aList[2] = 77
>>> print aList
[1, 2, 77, 4, 5, 6]
>>> aList[2:4] = ['a','b']
>>> print aList
[1, 2, 'a', 'b', 5, 6]


通过索引可以修改列表的一个数或一段数。

通过append(obj)增加

>>> aList.append('abc')
>>> print aList
[1, 2, 'a', 'b', 5, 6, 'abc']
>>>


append()实现在列表的末尾添加一个对象。

通过insert(index,obj)插入对象

>>> aList = [1,2,3,4,5,6]
>>> aList.insert(3,'a')  #在指定索引前插入对象
>>> print aList
[1, 2, 3, 'a', 4, 5, 6]
>>>


通过extend(iter)连接迭代对象

>>> aList = [1,2,3]
>>> bList = [2,3,4]
>>> aList.extend(bList)
>>> print aList
[1, 2, 3, 2, 3, 4]
>>> bList.extend(aList)
>>> print bList
[2, 3, 4, 1, 2, 3, 2, 3, 4]
>>> str1 = 'abc'    #字符串
>>> aTuple = (1,2,3,4)      #元组
>>> aDict = {'1':'a','2':'b'}   #字典
>>> print aList
[1, 2, 3, 2, 3, 4]
>>> aList.extend(str1)
>>> print aList
[1, 2, 3, 2, 3, 4, 'a', 'b', 'c']   #字符串会被拆分
>>> aList.extend(aTuple)
>>> print aList
[1, 2, 3, 2, 3, 4, 'a', 'b', 'c', 1, 2, 3, 4]
>>> aList.extend(aDict)
>>> print aList
[1, 2, 3, 2, 3, 4, 'a', 'b', 'c', 1, 2, 3, 4, '1', '2']  #字典只会连接字典的键
>>>


2. 删除列表

通过del删除

>>> aList = [1,2,3,4,5,6]
>>> del aList[1]  #删除指定下标的元素
>>> print aList
[1, 3, 4, 5, 6]
>>> del aList  #删除列表
>>> print aList
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print aList
NameError: name 'aList' is not defined
>>>


通过remove(value)移除

>>> aList = [1,2,3,4,5,6,7]
>>> print aList
[1, 2, 3, 4, 5, 6, 7]
>>> aList.remove(3)  #删除指定的对象
>>> print aList
[1, 2, 4, 5, 6, 7]
>>> aList.remove(3)     #找不到要移除的指定对象时,会提示错误。

Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
aList.remove(3)
ValueError: list.remove(x): x not in list
>>>


通过pop([index])抛出

>>> print aList
[1, 2, 4, 5, 6, 7]
>>> aList.pop()  #默认抛出(移除并返回这个索引对应的值)列表的最后一位
7
>>> print aList
[1, 2, 4, 5, 6]
>>> aList.pop(2)  #抛出指定索引的值
4
>>> aList.pop(6)  #索引不存在时会报错

Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
aList.pop(6)
IndexError: pop index out of range
>>>


3. 列表检索

index(value,[start,[stop]]) 默认查找value的索引值

一个参数时,只找到value在列表中第一次出现的索引

两个参数时,表示从start索引处开始,向后查找,找到第一个value的索引值

三个参数时,表示在start到stop索引区间(左闭右开)找第一个value的索引值

>>> aList = [1,2,3,1,2,3,1,2,3]
>>> aList.index(3)
2
>>> aList.index(3,3)
5
>>> aList.index(2,3,8)
4
>>> aList.index(1,1,2)

Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
aList.index(1,1,2)
ValueError: 1 is not in list
>>>


4. 元素统计

用count(value)统计指定对象值在列表中出现的次数

>>> aList = [1,2,3,1,2,3,1,2,3]
>>> print aList
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> aList.count(1)
3
>>>


5. 列表排序

reverse()列表反转

>>> aList = ['a','b','c','d','e','f']
>>> aList.reverse()
>>> print aList
['f', 'e', 'd', 'c', 'b', 'a']
>>>


sort(cmp=None, key=None,reverse=False)排序

>>> aList = ['e','d','a','b','c','g','f']
>>> aList.sort()
>>> print aList
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> aList = ['e','d','a','b','c','g','f']
>>> aList.sort(reverse = True)
>>> print aList
['g', 'f', 'e', 'd', 'c', 'b', 'a']
>>>


列表的简单应用

1. 用作栈

列表的方法使它使用列表作为栈很容易(根据栈的特点:后进先出)。添加元素到堆栈的顶部,用append()。从栈顶的检索项,使用pop()。例如:

>>> stack = [3, 4, 5]
>>> stack.append(6)   #入栈
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()  #出栈
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]


2. 用作队列

也可以用作队列(队列特点:先进先出)。列表是没有效率的,在插入和取出列表的末尾都快,做插入和弹出一个列表的开头是缓慢的(因为其他的元素都将产生移位)。

要实现队列,使用collections.deque的初衷是为了快速插入和取出的两端。例如:

>>> from collections import deque
#使用collections.deque的是为了加速两端的插入和取出
>>> from collections import deque
>>> queue = deque(["a","b","c"])
>>> queue
deque(['a', 'b', 'c'])
>>> queue.append("d");  #右端插入
>>> queue.append("e");
>>> queue
deque(['a', 'b', 'c', 'd', 'e'])
>>> queue.popleft()  #左端取出
'a'
>>> queue.pop()  #右端取出
'e'
>>> queue
deque(['b', 'c', 'd'])
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: