繼續List:
刪除元素:
代碼如下:
a =[1, 2, 3, 4]
a[2:3] = [] #[1, 2, 4]
del a[2] #[1, 2]
清空list
代碼如下:
a[ : ] = []
del a[:]
list作為棧使用(后入先出):
代碼如下:
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack.pop() # 7
stack.pop() # 6
stack.pop() # 5
用負數索引:
代碼如下:
b=[1, 2, 3, 4]
b[-2] #3
"+"組合list:
代碼如下:
end = ['st', 'nd'] + 5*['th'] + ['xy'] # ['st', 'nd', 'th', 'th', 'th', 'th', 'th', 'xy']
查出某元素在list中的數量:
代碼如下:
lst.('hello') # hello 的數量
list排序:
代碼如下:
sort()
#對鏈表中的元素進行適當的排序。
reverse()
#倒排鏈表中的元素
函數指針的問題:
代碼如下:
def f2(a, L=[])
L.append(a)
return L
print(f2(1)) # 1
print(f2(2)) # 1, 2 L在這次函數調用時是[1]
print(f2(3)) # 1, 2, 3
函數中的參數中有:
*參數名 :表示任意個數的參數
** ?。罕硎綿ictionary參數
控制語句:
IF:
代碼如下:
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
FOR:
代碼如下:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
WHILE:
代碼如下:
a, b = 0, 1
while b < 1000:
print b,
a, b = b, a+b
#1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
pass :空操作語句
代碼如下:
while True:
pass
dictionary: 鍵值對的數據結構
用list來構造dictionary:
代碼如下:
items = [('name', 'dc'), ('age', 78)]
d = dict(items) #{'age': 78, 'name': 'dc'}
有趣的比較:
代碼如下:
x = [] #list
x[2] = 'foo' #出錯
x = {} #dictionary
x[2] = 'foo' #正確
內容比較雜,學到什么就記下來。完全利用工作中的空閑和業余時間來完成,更加充實了。