因为列表具有pop、append、insert方法,因此列表可以当作堆、栈使用。由于性能问题,不建议当作堆。(堆:队列优先,先进先出(FIFO—first in first out)栈:先进后出(FILO—First-In/Last-Out))
列表的pop、insert方法,使得列表可以当作队列使用,先入先出,但是在列表的开头做插入或者弹出都非常慢,因为要移动其他元素。需要用到队列,建议使用collections.deque。
可以使用map来创建队列,map(func,*iterables)
>>> list(map(lambda x:x**2,range(23)))
[0,1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484]
创建列表的"[ ]",可以包含复杂的表达式,和嵌套函数
>>> test=[ x**2 for x in range(3) ]>>>test
[0,1, 4]
列表删除元素方法及删除列表方法:remove、pop、clear、del。remove与pop都只能删除一个元素、clear清空列表。del可以切片删除。
>>> test=[0,1,2,3,4]>>> test.remove(3)>>>test
[0,1, 2, 4]
>>> test=[0,1,2,3,4]
>>> test.pop()
4
>>> test
[0, 1, 2, 3]
>>>
>>> test.pop(1)
1
>>> test
[0, 2, 3]
>>>
>>> test=[0,1,2,3,4]
>>> test.clear()
>>> test
[]
>>> test=[0,1,2,3,4]
>>> del test[0:2]
>>> test
[2, 3, 4]
>>> del test[:]
>>> test
[]
>>> del test
>>> test
Traceback (most recent call last):
File "", line 1, in
NameError: name 'test' is not defined
>>>
序列主要以下几种类型:
3种基本序列类型(Basic Sequence Types):list、tuple、range (补:range() 函数返回的结果是一个整数序列的对象,而不是列表。tuple就是元组)
专门处理文本的附加序列类型(Text Sequence Types):str
专门处理二进制数据的附加序列类型(Binary Sequence Types): bytes、bytearray、memoryview
按照序列是否可被改变分类:
可变序列: list
不可变序列:tuple、str
tuple元组是标准的序列类型,不支持个别项目分配
>>> a=6,7,8,89,9
>>>a
(6, 7, 8, 89, 9)>>> a[0]=2Traceback (most recent call last):
File"", line 1, in TypeError:'tuple' object does notsupport item assignment>>>
但是tuple可以包含可变对象
>>> a=43,4,5,6,[4,4,4,4]>>>a
(43, 4, 5, 6, [4, 4, 4, 4])>>> a[4][0]=99999
>>>a
(43, 4, 5, 6, [99999, 4, 4, 4])>>>
tuple的创建,当为空元素和一个元素的情况
>>> a=()>>>a
()>>> a=0,>>>a
(0,)>>>
tuple的解压缩
>>> a,b,c=3,4,5
>>>a3
>>>b4
>>>c5
>>>
tuple的打包
>>> a=3,4,5,5
>>>a
(3, 4, 5, 5)>>>
字典的键必须是不可变的对象,例如字符串、数字、元组且元祖不能直接或间接的包含可变对象。字典的健不可以为列表,因为列表可以使用索引分配、del 切片 、append、extend等方法更改list对象。
想要在相反的情况下循环一个列表,可以使用reversed函数
>>> for i in reversed(range(1,6,1)):
...print(i)
...5
4
3
2
1
>>>
is 、 is not 判断元素是否相等
>>> a=[]>>> b=[]>>> a isb
False>>> a=9
>>> b=9
>>> a isb
True>>> a is notb
False>>>
in、not in 判断是否在某个序列里
>>> test="basecee"
>>> 'a' intest
True>>> 'f' intest
False>>> 'f' not intest
True>>> "ba" intest
True
所有的比较运算符都有相同的优先级,比所有的数值运算符都要低。 这里‘< ,>’优先级低于‘+’
>>> 6+8>12True>>> 13<6+9True>>>
布尔运算符的优先级低于比较运输符
>>> 12==10 or 10==10True>>> 10>5 and 9<0
False>>>