《笨辦法學(xué)Python》 第38課手記
注意這是第三版的《笨辦法學(xué)Python》的內(nèi)容,我后來發(fā)現(xiàn)第三版存在很大的問題,就放棄了第三版開始使用第四版,第四版的第38課是讀代碼,這里保留之前的手記,因為它們是有價值。
不在寫第四課的手記,因為是讀代碼課。但是之后的課程手記全部是針對第四版的,第三版棄之不用了。
本節(jié)課內(nèi)容較多,可以慢慢理解,雖然標(biāo)題是列表,但實際其實是一種叫做字典(dict)的數(shù)據(jù)結(jié)構(gòu)。
列表是有序排列的一些物件,而字典是將一些物件(keys)對應(yīng)到另外一些物件(values) 的數(shù)據(jù)結(jié)構(gòu)。這句話出自39課的常見問題解答。
原代碼如下(縮進(jìn)統(tǒng)一使用四個空格):
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI',
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
# print some states
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# do it by using the states then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
# print every city in state
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas', None)
if not state:
print "Sorry, no Texas."
# get a city with a default values
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
結(jié)果如下:
一塊一塊地來解釋吧。
首先定義了字典,這里有兩種定義(事實上第二種是在添加字典中的元素)的方式。
①
第一種:
states = {
‘Oregon’: ‘OR’,
‘Florida’: ‘FL’,
‘California’: ‘CA’,
‘New York’: ‘NY’,
‘Michigan’: ‘MI’,
}
第二種:
cities[‘NY’] = ‘New York’
cities[‘OR’] = ‘Portland’
而在使用時,以states[‘縮寫’]的形式即可表示相應(yīng)的字符串,這比數(shù)組強大的多,數(shù)組只能以基數(shù)來區(qū)分其中的元素,列表以縮寫來區(qū)分,顯然方便的多,使用時不再要求你記住數(shù)值,縮寫是你在學(xué)英語時以及記住的東西。
②
print ‘-’ * 10
print “Michigan has: “, cities[states[‘Michigan’]]
print “Florida has: “, cities[states[‘Florida’]]
這里是嵌套調(diào)用,因為states和cities是在定義時就是嵌套定義的,所以可以嵌套使用,請記住這個用法。
③
print ‘-’ * 10
for state, abbrev in states.items():
print “%s is abbreviated %s” % (state, abbrev)
abbrev也是一個關(guān)鍵字,是指列表中元素的縮寫。states.item()會遍歷states里面的所有內(nèi)容。
④
state = states.get(‘Texas’, None)
這里涉及到get函數(shù)。
描述:
Python 字典(Dictionary) get() 函數(shù)返回指定鍵的值,如果值不在字典中返回默認(rèn)值。
語法:
dict.get(key, default=None)
參數(shù):
key – 字典中要查找的鍵。
default – 如果指定鍵的值不存在時,返回該默認(rèn)值值。
返回值:
返回指定鍵的值,如果值不在字典中返回默認(rèn)值None。None是一個邏輯值,表示為假。所以if語句滿足運行的條件,而最后一塊代碼中變量city中儲存的值不是一個邏輯值而是字符串。
本節(jié)課涉及的知識
其實本節(jié)課這種類型的列表變量還有專門的名字叫做字典(dict),字典由鍵和值組成,鍵是數(shù)據(jù)庫里面的鍵(key),相當(dāng)于我們?nèi)粘I钪凶值涞捻摯a,是一種索引或者說地址,每一個鍵都對應(yīng)一個值。
Operation | Result |
---|---|
len(a) | the number of items in a 得到字典中元素的個數(shù) |
a[k] | the item of a with key k 取得鍵K所對應(yīng)的值 |
a[k] = v | set a[k] to v 設(shè)定鍵k所對應(yīng)的值成為v |
del a[k] | remove a[k] from a 從字典中刪除鍵為k的元素 |
a.clear() | remove all items from a 清空整個字典 |
a.copy() | a (shallow) copy of a 得到字典副本 |
k in a | True if a has a key k, else False 字典中存在鍵k則為返回True,沒有則返回False |
k not in a | Equivalent to not k in a 字典中不存在鍵k則為返回true,反之返回False |
a.has_key(k) | Equivalent to k in a, use that form in new code 等價于k in a |
a.items() | a copy of a’s list of (key, value) pairs 得到一個鍵值的list |
a.keys() | a copy of a’s list of keys 得到鍵的list |
a.update([b]) | updates (and overwrites) key/value pairs from b 從b字典中更新a字典,如果鍵相同則更新,a中不存在則追加 |
a.fromkeys(seq[, value]) | Creates a new dictionary with keys from seq and values set to value 創(chuàng)建一個新的字典,鍵來自seq,值對應(yīng)鍵對應(yīng)的值 |
a.values() | a copy of a’s list of values 得到字典值的副本 |
a.get(k[, x]) | a[k] if k in a, else x 得到a[k],若存在返回x |
a.setdefault(k[, x]) | a[k] if k in a, else x (also setting it) 得到a[k],若不存在返回x,并設(shè)定為x |
a.pop(k[, x]) | a[k] if k in a, else x (and remove k) 彈出a[k],若不存在則返回x,同時將刪除k鍵 |
a.popitem() | remove and return an arbitrary (key, value) pair 彈出a中對象的鍵和值,并刪除彈出的鍵和值 |
a.iteritems() | return an iterator over (key, value) pairs 返回a中所有對象(鍵和值) |
a.iterkeys() | return an iterator over the mapping’s keys 返回a中所有鍵(索引) |
a.itervalues() | return an iterator over the mapping’s values 返回a中所有值 |
建議每天看一遍,一個星期之后就能牢記于心。也可以先記住本機(jī)課涉及的內(nèi)容,碰到字典再來翻這一節(jié)課。