以Mark Lutz著的《Python學習手冊》爲教程,每天花1個小時左右時間學習,爭取兩週完成。 --- 寫在前面的話
2013-7-18 19:00 學習筆記
1,Python中的列表是任意對象的有序集合,而且是可變的。在標準的Python解釋器內部,列表是C數組,不是鏈接結構。
2,列表的一些基本操作與字符串很類似,因爲它們本質上都是一種序列。例如:
L1 = [1,2,3]
L2= [4,5,6]
print len(L1)
print L1 + L2
print L1*2
print 3 in L1,2 in L2
for x in L1: print x
結果爲:
3
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3]
True False
1
2
3
而對於+操作,要注意+兩邊要爲同樣的類型,否則應使用str()將列表轉爲字符串,或使用list()將字符串轉爲列表。例如:
print str([1,2]) + '34'
print [1,2] + list('34')
結果爲:
[1, 2]34
[1, 2, '3', '4']
3,與字符串不同,列表是可以改變。例如:
L = [1,2,3,4,5,6]
L[1] = 99
print L
L[2::2] = [77,88]
print L
例如:
[1, 99, 3, 4, 5, 6]
[1, 99, 77, 4, 88, 6]
4,列表有許多方法,例如append()、sort()、extend()、pop()等等,可以查手冊和文檔,這裏不說了。值得一提的是del(),它可以刪除列表中的元素。例如:
L = [1,2,3,4,5,6]
print L
del L[1]
print L
del L[3:]
print L
結果爲:
[1, 2, 3, 4, 5, 6]
[1, 3, 4, 5, 6]
[1, 3, 4]
5,在Python中,字典是任意對象的無序集合,通過鍵而不是偏移量來讀取。字典可以改變。字典本質是哈希表。
6,創建字典有4種方法:
# method 1
L1 = {'name':'mathboy', 'age':23}
# method 2
L2 = {}
L2['name'] = 'mathboy'
L2['age'] = 23
# method 3
L3 = dict(name='mathboy', age=23)
# method 4
L4 = dict([('name','mathboy'), ('age',23)])
7,字典中也有很多的方法。例如has_key()判斷是否存在某個鍵,values()返回值的列表,keys()返回鍵的列表,items()返回元組列表。
D = {'boy': 'mathboy', 'girl': 'mo'}
print D.has_key('name')
print D.keys()
print D.values()
print D.items()
輸出結果爲:
False
['boy', 'girl']
['mathboy', 'mo']
[('boy', 'mathboy'), ('girl', 'mo')]
8,字典的鍵也可以是數字。例如:
D = {}
D[1] = 'mathboy'
key = 3
D[key] = 'mo'
print D
結果爲:
{1: 'mathboy', 3: 'mo'}