list
list.append(x)
>>> a=[1,2,3]
>>> a.append(4) #列表追加元素
>>> a
[1, 2, 3, 4]
>>> a[len(a):]=[4] # Equivalent to a[len(a):] = [x]
>>> a
[1, 2, 3, 4, 4]
list.extend(iterable)
>>> a=[1,2,3]
>>> a.extend(range(5,8)) #迭代对象中的所有元素都添加到列表后面
>>> a
[1, 2, 3, 5, 6, 7]
>>> a.extend([11,12,13])
>>> a
[1, 2, 3, 5, 6, 7, 11, 12, 13]
>>> a[len(a):]=range(100,105) # Equivalent to a[len(a):] = iterable
>>> a
[1, 2, 3, 5, 6, 7, 11, 12, 13, 100, 101, 102, 103, 104]
list.insert(i, x)
>>> a=[1,2,3]
>>> a.insert(0,"a") #插在开头
>>> a
['a', 1, 2, 3]
>>> a.insert(len(a),"b") #加在结尾,equivalent to a.append(x)
>>> a
['a', 1, 2, 3, 'b']
list.remove(x)
>>> a=[1,2,3,1,2,3]
>>> a.remove(1) #删除第一个相等的元素
>>> a
[2, 3, 1, 2, 3]
>>> a.remove(11) #不存在时,报错:ValueError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
list.pop([i])
参数可选,i指定抛出的位置(index),默认抛出最后一个元素;并返回被抛出的元素
>>> a=[1,2,3,4,5]
>>> b=a.pop() #
>>> b
5
>>> a
[1, 2, 3, 4]
>>>
>>> b=a.pop(2) #抛出指定位置的元素
>>> b
3
>>> a
[1, 2, 4]
list.clear()
清空所有元素
>>> a=[1,2,3]
>>> a.clear() #清空所有元素
>>> a
[]
>>> a=[1,2,3]
>>> del a[:] # Equivalent to del a[:]
>>> a
[]
list.index(x[, start[, end]])
查找元素x的索引,start和end限制查找的范围在他两组成的子序列中
>>> a=[1,2,3,4,1,2,3,4,4,4]
>>> a.index(4) #查找4第一次出现的索引位置
3
>>> a.index(4,4)
7
>>> a.index(4,7)
7
list.count(x)
统计元素x出现的次数
>>> a=[1,2,3,4,1,2,3,4,4,4]
>>> a.count(4)
4
>>> a.count(3)
2
list.sort(key=None, reverse=False)
排序,参数说明见sorted内建函数
>>> a=[3,2,1,0]
>>> a.sort() #排序
>>> a
[0, 1, 2, 3]
list.reverse()
>>> a=[1,2,3]
>>> a.reverse() #翻转
>>> a
[3, 2, 1]
list.copy()
shallow copy :浅拷贝
>>> a=[1,2,3]
>>> b=a.copy()
>>> b
[1, 2, 3]
>>> c=a[:] # Equivalent to a[:]
>>> c
[1, 2, 3]
列表做堆栈
后进先出,pop()和append()方法
>>> a=[1,2,3]
>>> a.append(4)
>>> a.append(5)
>>> a
[1, 2, 3, 4, 5]
>>> a.pop()
5
>>> a.pop()
4
>>> a
[1, 2, 3]
列表做队列
左边操作时效率不高
>>> from collections import deque
>>> queue=deque(["A","BB","CC"])
>>> queue.append("DD")
>>> queue.append("EE")
>>> queue
deque(['A', 'BB', 'CC', 'DD', 'EE'])
>>> queue.popleft()
'A'
>>>
>>> queue.popleft()
'BB'
>>> queue
deque(['CC', 'DD', 'EE'])
列表解析
>>> list(map(lambda x:x**2,range(10)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x**2 for x in range(10)] #列表解析
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [(x,y) for x in [1,2,3] for y in [3,1,2] if x != y ] #列表解析
[(1, 3), (1, 2), (2, 3), (2, 1), (3, 1), (3, 2)]
>>>
>>>
>>> arr=[] #与上述解析等价:
>>> for x in [1,2,3]:
... for y in [3,1,2]:
... if x != y:
... arr.append((x,y))
...
>>> arr
[(1, 3), (1, 2), (2, 3), (2, 1), (3, 1), (3, 2)]
嵌套列表解析
m=[
... [1,2,3,4],
... [5,6,7,8],
... [9,10,11,12] ]
>>> m
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
>>>
>>>
>>> [[row[i] for row in m] for i in range(4)] #嵌套列表解析
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
a=[] #与上述解析等价:
>>> for i in range(4):
... a.append([row[i] for row in m])
...
>>> a
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> list(zip(*m)) #内建zip()
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
del
>>> a=[1,2,3,4,5,6,7]
>>> del a[0] #删除单个元素
>>> a
[2, 3, 4, 5, 6, 7]
>>> del a[1:3] #删除多个连续的元素
>>> a
[2, 5, 6, 7]
>>> del a[:] #清空所有元素
>>> a
[]
>>> del a #删除变量
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
tuple
>>> a='hello','world','Tony' #a为元组
>>> a
('hello', 'world', 'Tony')
>>> a[0] #访问第一个元素
'hello'
>>>
>>> b=a,(1,2,3) #元组赋值
>>> b
(('hello', 'world', 'Tony'), (1, 2, 3))
>>> b[0]=1 #元组不可变
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
>>> a=() #空元组
>>> b=(1,) #单元素的元组,括号可不加,逗号要加
>>> len(a)
0
>>> type(b) #获取类型
<class 'tuple'>
>>>
>>> a='hello','world','Tony'
>>> x,y,z=a #元组赋值给多个变量
>>> x
'hello'
set
集合:无序,无重复元素
创建:花括号或者set()方法;空集合只能是set()
>>> a=set() #空集合
>>> type(a)
<class 'set'>
>>> a={1,2,3,4} #通过花括号创建
>>> a
{1, 2, 3, 4}
>>> 1 in a #判断元素是否存在于集合中
True
>>> 5 in a
False
>>> a = set('abracadabra') #通过set()方法创建集合
>>> b = set('alacazam')
>>> a
{'r', 'd', 'b', 'a', 'c'}
>>> b
{'m', 'l', 'a', 'z', 'c'}
>>> a-b #差集
{'d', 'r', 'b'}
>>> a|b #并集
{'r', 'm', 'l', 'd', 'a', 'b', 'z', 'c'}
>>> a^b #亦或
{'r', 'z', 'l', 'd', 'b', 'm'}
>>> a&b #交集
{'c', 'a'}
集合解析
>>> a={x for x in 'abcdefg abcdefg' if x not in 'abc'}
>>> a
{'f', 'd', ' ', 'g', 'e'}
dict
字典
键值可以为数字或字符串
>>> a={} #空字典
>>> type(a)
<class 'dict'>
>>> b={1.1:"first day",10.1:'national day',"tiger":"animal"} #创建
>>> b
{1.1: 'first day', 10.1: 'national day', 'tiger': 'animal'}
>>> b['apple']=11 #增加键值对
>>> b
{1.1: 'first day', 10.1: 'national day', 'tiger': 'animal', 'apple': 11}
>>> del b['apple'] #删除键值对
>>> b
{1.1: 'first day', 10.1: 'national day', 'tiger': 'animal'}
>>> b['tiger']='is not cat' #修改
>>> b
{1.1: 'first day', 10.1: 'national day', 'tiger': 'is not cat'}
>>> b['tiger'] #访问,查询
'is not cat'
>>> list(b) #获取keys
[1.1, 10.1, 'tiger']
>>> sorted(b) #sorted() 返回排序的键列表(必须能够比较,否则报错:)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'float'
>>> 1.1 in b #in
True
>>> 1.1 not in b #not in
False
字典的其他创建方式
>>> dict([('a',97),('b',98),('c',99) ]) #
{'a': 97, 'b': 98, 'c': 99}
>>>
>>> {x:x**3 for x in range(6)} #
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
>>> dict(k1=1,k2=2,k3='333') #
{'k1': 1, 'k2': 2, 'k3': '333'}
>>> dict(5=125,6=216)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
循环技巧
字典:items()
d={"apple":"red","banaba":"yellow"}
for key,value in d.items(): #包含键和值
print(key,value)
输出:
apple red
banaba yellow
列表:enumerate()
for index,value in enumerate(["a","b","c"]): #包含索引和值
print(index,value)
输出:
0 a
1 b
2 c
同时迭代两个序列:zip()
fruit=["apple","banaba"]
color=["red","yellow"]
for f,c in zip(fruit,color):
print(f,c)
输出:
apple red
banaba yellow
反向迭代:reversed()
for i in reversed(range(1, 10, 2)):
print(i,end=" ")
输出:9 7 5 3 1
排序后迭代:sorted()
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
输出:
apple
banana
orange
pear
while,if条件判断
in,not in :判断值是否存在于序列中
is ,not is :判断两对象是否为同一对象
布尔操作符:and(为短路与),or(为短路或),not
序列及其他类型的比较
比较的是同种类型
>>> (1,2,3)<(1,2,4)
True
>>> (1,2)<(2,3)
True
>>> [1,2]<[1,1,4]
False
>>> "abc"<"cdv"
True
>>> (1,2,3)==(1.0,2.0,3.0) #
True