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