字典和集合
字典基礎操作
創建字典
通過{}操作符創建字典
通過dict()工廠函數創建字典
通過fromkeys()創建具有相同值的默認字典
>>> aDict = {'Name':'Bob','age':23}
>>> import tab
>>> bDict = dict((['name','bob'],['age',23]))
>>> print bDict
{'age': 23, 'name': 'bob'}
>>> cDict = {}.fromkeys(('bob','alice'),23)
>>> print cDict
{'bob': 23, 'alice': 23}
>>> dict(['ab','cd','ef'])
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> dict([('name','bob'),('age',20),['qq','123455']])
{'qq': '123455', 'age': 20, 'name': 'bob'}
訪問字典
字典是映射類型,意味着它沒有下標,訪問字典中的值需要使用相應的鍵
>>> adict
{'age': 20, 'name': 'bob'}
>>> for eachKey in adict:
... print "key = %s,value = %s" % (eachKey,adict[eachKey])
...
key = age,value = 20
key = name,value = bob
>>> print "%(name)s" %adict
bob
更新字典
通過鍵更新字典
- 如果字典中有該鍵,則更新相關值
- 如果字典中無該鍵,則向字典中添加新值
>>> print adict
{'age': 20, 'name': 'bob'}
>>> adict['age'] = 22
>>> print adict
{'age': 22, 'name': 'bob'}
>>> adict['email']='[email protected]'
>>> print adict
{'age': 22, 'name': 'bob', 'email': '[email protected]'
刪除字典
通過del可以刪除字典中的元素或整個字典
使用內部方法clear()可以清空字典
使用pop()方法“彈出”字典中的元素
>>> print adict
{'age': 22, 'name': 'bob', 'email': '[email protected]'}
>>> del adict['email']
>>> print adict
{'age': 22, 'name': 'bob'}
>>> adict.pop('age')
22
>>> print adict
{'name': 'bob'}
>>> adict.clear()
>>> print adict
{}
>>> adict = {'name':'bob','age':20}
>>> adict
{'age': 20, 'name': 'bob'}
>>> adict.popitem() #隨機pop出一個鍵值,不常用,因爲它不接受參數。
('age', 20)
>>> adict
{'name': 'bob'}
>>> adict.popitem('bob')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: popitem() takes no arguments (1 given)
字典操作符
使用字典鍵查找操作符[keyname],查找鍵所對應的值
使用in 和not in 判斷鍵是否存在於字典中
>>> adict = {'name':'bob','age':20}
>>> print adict['name']
bob
>>> adict
{'age': 20, 'name': 'bob'}
>>> 'bob' in adict
False
>>> 'name'in adict
True
字典相關函數
作用於字典的函數
len():返回字典中元素的數目
hash():本身不是爲字典設計的,但是可以判斷某個對象是否可以作爲字典的鍵
>>> print adict
{'age': 20, 'name': 'bob'}
>>> print len(adict)
2
>>> hash(3) # 不報錯的說明可以作爲字典的鍵,報錯則不能作爲字典的鍵
3
>>> hash([]) #總結:不可變類型可以作爲字典的key,可變的 不行
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash('name')
15034981
>>> hash((10,20))
-95038731
字典內建方法
dict.copy():返回字典(淺複製(只複製值,id不同))的一個副本
>>> print adict
{'age': 20, 'name': 'bob'}
>>> bDict = adict.copy()
>>> bDict
{'age': 20, 'name': 'bob'}
>>> bDict['name'] = 'alice'
>>> print bDict
{'age': 20, 'name': 'alice'}
####################
>>> adict
{'age': 20, 'name': 'bob'}
>>> bdict = adict
>>> bdict['age'] = 22
>>> bdict
{'age': 22, 'name': 'bob'}
>>> adict
{'age': 22, 'name': 'bob'}
dict.get(key,default=None):對字典dict中的鍵key,返回它對應的值value,如果字典中不存在此鍵,則返回default的值
>>> print adict
{'age': 22, 'name': 'bob'}
>>> adict.get('name','not found')
'bob'
>>> adict.get('email','not found')
'not found'
dict.items(): 返回一個包含字典中(鍵,值)對元組的列表
dict.keys():返回一個包含字典中鍵的列表
>>> adict.keys()
['qq', 'age', 'name']
dict.values():返回一個包含字典中所有值的列表
>>> adict.values()
['2222333', 22, 'bob']
dict.update(dict2):將字典dict2的鍵-值對添加到字典dict
>>> adict.update({'phone': '12345678901','emali': '[email protected]'})
>>> adict
{'qq': '2222333', 'phone': '12345678901', 'age': 22, 'name': 'bob', 'emali': '[email protected]'}
dict.setdefault():安全在字典中添加key-value,字典中已存在的key-value不會覆蓋
>>> adict
{'age': 22, 'name': 'bob'}
>>> adict.setdefault('age',30)
22
>>> adict
{'age': 22, 'name': 'bob'}
>>> adict.setdefault('qq','2222333')
'2222333'
>>> adict
{'qq': '2222333', 'age': 22, 'name': 'bob'}
習題:
用戶登錄信息系統
使用字典模擬一個用戶登錄信息系統
1、支持新用戶註冊,新用戶名和密碼註冊到字典中
2、支持老用戶登錄,用戶名和密碼正確提示登錄成功
3、主程序通過循環詢問進行何種操作,根據用戶的選擇,執行註冊或是登錄操作
集合
集合類型
數學上,把set稱作由不同的元素組成的集合,集合(set)的成員通常被稱作集合元素
集合對象是一組無序排列的可哈希的值
集合有兩種類型
- 可變集合set
- 不可變結合 frozenset
>>> s1 = set('hello')
>>> s2 = frozenset('hello')
>>> s1
set(['h', 'e', 'l', 'o'])
>>> s2
frozenset(['h', 'e', 'l', 'o'])
集合類型操作符
集合支持用in和not in 操作符檢查成員
能夠通過len()檢查集合大小
能夠使用for迭代集合成員
不能切片,沒有鍵
>>> s2
frozenset(['h', 'e', 'l', 'o'])
>>> len(s2)
4
>>> for ch in s2:
... print ch
...
h
e
l
o
|:聯合,取並集
&:交集
-:差補
>>> s1 = set('abc')
>>> s2 = set('cde')
>>> s1 | s2
set(['a', 'c', 'b', 'e', 'd'])
>>> s1 & s2
set(['c'])
>>> s1 - s2
set(['a', 'b'])
集合內建方法
set.add():添加成員
set.update():批量添加成員
set.remove():移除成員
>>> print s1
set(['a', 'c', 'b'])
>>> s1.add('new')
>>> print s1
set(['a', 'new', 'c', 'b'])
>>> s1.update('new')
>>> print s1
set(['a', 'c', 'b', 'e', 'n', 'w', 'new'])
>>> s1.update(['new','world'])
>>> print s1
set(['a', 'c', 'b', 'e', 'n', 'world', 'new'])
>>> s1.remove('n')
>>> print s1
set(['a', 'c', 'b', 'e', 'w', 'new'])
s.issubset(t):如果s是t的子集,則返回True,否則返回False
s.issuperset(t):如果t是s的超集,則返回True,否則返回False
s.union(t):返回一個新集合,該集合是s和t的並集
s.intersection(t):返回一個新集合,該集合是s和t的交集
s.difference(t):返回一個新集合,該集合是s的成員,但不是t的成員
>>> s1 = set('abc')
>>> s3 = set('abcdef')
>>> s1
set(['a', 'c', 'b'])
>>> s3
set(['a', 'c', 'b', 'e', 'd', 'f'])
>>> s1.issubset(s3)
True
>>> s3.issuperset(s1)
True
>>> s1
set(['a', 'c', 'b'])
>>> s2
set(['c', 'e', 'd'])
>>> s1.union(s2)
set(['a', 'c', 'b', 'e', 'd'])
>>> s1.intersection(s2)
set(['c'])
>>> s1.difference(s2)
set(['a', 'b'])
條件和循環
if語句
if基本語法結構
if判斷語句是在python程序中經常用到的句法,其基本語法結構如下
if expression:
expr_true_suite
else:
expr_false_suite
如果代碼塊僅包含一行代碼,也可以和前面的寫在一行,但是可讀性較差,不建議使用
if expression: expr_true_sutie
多重條件
單個if語句可以通過使用布爾操作符and,or和not實現多重判斷條件或是否定判斷條件
爲了實現更好的可讀性,可以使用()分組,但是python並不強制這麼做
if not warn and (system_load >= 10):
print "Warning: losing resources"
warn +=1
elif語句
檢查多個表達式是否爲真,並在爲真時執行特定代碼塊中的代碼
沒有case或switch語句,可以使用其他數據結構模擬
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expressioN:
exprN_true_suite
else:
none_of_the_above_suite
習題2:
模擬case句法
編寫一個程序,模擬case語句功能
1、提示用戶輸入執行何種操作(create/delete/modify)
2、如果輸入爲create,則打印create user
3、如果輸入爲delete,則打印delete user
4、如果輸入爲modify,則打印modify user
5、否則打印input error
條件表達式
python 在很長的一段時間裏沒有條件判斷式(C ? X: Y),或稱三元運算符,因爲範.羅薩姆一直拒絕加入這樣的功能
從Python2.5集成的語法確定爲: X if C else Y
>>> x,y=3,4
>>> smaller = x if x<y else y
>> print smaller
3
循環語句
while語句
while循環的語法如下:
while expression:
suite_to repeat
通常在當循環次數不確定時使用while循環
for語句
for循環會訪問一個可迭代對象中的所有元素,並在所有條目都處理過後結束循環,它的語法如下:
for iter_var in iterable:
suite_to repeat
通常在循環次數已知的情況下,會採用for循環
else 語句
與其他語言不同,python的while和for語句還支持else語句
只有循環體正常結束時,else的代碼塊纔會執行
如果循環體內的代碼被中斷,那麼else代碼塊也被中斷,不會執行
while expression:
suite_to_repeat
else:
else_clause
break語句
break 語句可以結束當前循環,然後跳轉到循環以下語句
可以用在while和for循環中
一般通過if語句檢查,當某個外部條件被觸發立即從循環中退出
>>> while True:
... username = raw_input("username: ")
... if username =='bob':
... break
...
username: bob
>>>
continue語句
當遇到continue語句時,程序會終止當前循環,並忽略剩餘的語句,然後回到循環的頂端
在開始下一次循環前,如果是條件循環,將驗證條件表達式;如果是迭代循環,將驗證是否還有元素可以迭代
只有在驗證成功後,纔會開始下一次迭代或循環
>>> for i in range(5):
... if i %2:
... continue
... print i
...
0
2
4
pass語句
python沒有傳統的大括號來標記代碼塊,有時有些地方在語法上要求要有大媽塊
python提供了pass語句,他不做任何事情
>>> def foo():
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
>>> def foo():
... pass
...
迭代
迭代器和iter()函數
爲類序列對象提供了一個類序列的接口
從根本上說,迭代器就是有一個next()方法的對象
python的迭代無縫第支持序列對象,而且它還允許程序員迭代非序列類型
不能向後移動或回到開始,也不能複製一個迭代器。
>>> myiter = iter('hello')
>>> myiter
<iterator object at 0xb70ed78c>
>>> myiter.next()
'h'
>>> myiter.next()
'e'
>>> myiter.next()
'l'
>>> myiter.next()
'l'
>>> myiter.next()
'o'
>>> myiter.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> myiter = iter('hello')
>>> for ch in myiter:
... print ch,
...
h e l l o
對一個對象調用iter()就可以得到它的迭代器
當迭代器條目全部取出後會引發一個StopIteration異常,但這並不代表錯誤發生,只是告訴外部調用者迭代完成
插曲:xrange,range的區別
>>> xrange(100)
xrange(100)
>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]