Chapter 8 Lists and Dictionaries
1, list的concatenation 和 repetition 操做:express
>>> [1, 2, 3] + [4, 5, 6] # Concatenation [1, 2, 3, 4, 5, 6] >>> ['Ni!'] * 4 # Repetition ['Ni!', 'Ni!', 'Ni!', 'Ni!']
2,list是mutable sequence,能夠作in place assignment.
A, 單一賦值:app
>>> L = ['spam', 'Spam', 'SPAM!'] >>> L[1] = 'eggs' # Index assignment >>> L ['spam', 'eggs', 'SPAM!']
B,用slice給多個item賦值函數
>>> L[0:2] = ['eat', 'more'] # Slice assignment: delete+insert >>> L # Replaces items 0,1 ['eat', 'more', 'SPAM!']
雖然[0:2]僅包含2個item,可是,從新賦值的時候能夠賦給不止2個,或者少於2個,其實應該這樣認識slice assignment:
Step 1:將slice裏面的items刪除;
Step 2:將要賦值的新的sublist插入。
因此刪除的item的個數能夠和插入的item的個數不一致。oop
3,如何extend一個list?
方法一:使用slice assignment:ui
>>> L [2, 3, 4, 1] >>> L[len(L):] = [5, 6, 7] # Insert all at len(L):, an empty slice at end >>> L [2, 3, 4, 1, 5, 6, 7]
方法二:使用extend方法spa
>>> L.extend([8, 9, 10]) # Insert all at end, named method >>> L [2, 3, 4, 1, 5, 6, 7, 8, 9, 10]
方法三:使用append方法code
>>> L = ['eat', 'more', 'SPAM!'] >>> L.append('please') # Append method call: add item at end >>> L ['eat', 'more', 'SPAM!', 'please']
4,sort()按升序或降序排列orm
L = [2, 3, 4, 1] L.sort() #表示升序 L [1, 2, 3, 4] L.sort(reverse = True) #表示降序 L [4, 3, 2, 1]
Sort和 append會返回None。因此把他們賦給其餘變量,不然那個變量將變爲None。ip
5,有一個sorted函數也能夠作這樣的事情,並返回一個list:ci
>>> L = ['abc', 'ABD', 'aBe'] >>> sorted([x.lower() for x in L], reverse=True) # Pretransform items: differs! ['abe', 'abd', 'abc']
6,reverse能夠用來倒序:
>>> L [1, 2, 3, 4] >>> L.reverse() # In-place reversal method >>> L [4, 3, 2, 1] >>> list(reversed(L)) # Reversal built-in with a result (iterator) [1, 2, 3, 4]
7,index, insert, remove, pop, count
>>> L = ['spam', 'eggs', 'ham'] >>> L.index('eggs') # Index of an object (search/find) 1 >>> L.insert(1, 'toast') # Insert at position >>> L ['spam', 'toast', 'eggs', 'ham'] >>> L.remove('eggs') # Delete by value >> L ['spam', 'toast', 'ham'] >>> L.pop(1) # Delete by position 'toast' >>> L ['spam', 'ham'] >>> L.count('spam') # Number of occurrences 1
8, del函數不只能夠刪除一個item,還能夠刪除一個section。
>>> L = ['spam', 'eggs', 'ham', 'toast'] >>> del L[0] # Delete one item >>> L ['eggs', 'ham', 'toast'] >>> del L[1:] # Delete an entire section >>> L # Same as L[1:] = [] ['eggs']
而remove僅能刪除一個item。
9,給某個section賦值一個空List,也就至關於刪除該section:L[i:j]=[]
10,dictionary使用key來index:
>>> D = {'spam': 2, 'ham': 1, 'eggs': 3} # Make a dictionary >>> D['spam'] # Fetch a value by key 2 >>> D # Order is "scrambled" {'eggs': 3, 'spam': 2, 'ham': 1}
11,dictionary的keys方法返回dictionary的全部key 值:
>>> len(D) # Number of entries in dictionary 3 >>> 'ham' in D # Key membership test alternative True >>> list(D.keys()) # Create a new list of D's keys ['eggs', 'spam', 'ham']
#能夠不用list()方法,由於在Python 2.x keys的值原本就是list
12,在dictionary中,給一個key賦值新的value:
>>> D {'eggs': 3, 'spam': 2, 'ham': 1} >>> D['ham'] = ['grill', 'bake', 'fry'] # Change entry (value=list) >>> D {'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']}
13, 刪除某個entry,經過key
>>> del D['eggs'] # Delete entry >>> D {'spam': 2, 'ham': ['grill', 'bake', 'fry']}
14,增長一個新的entry:
>>> D['brunch'] = 'Bacon' # Add new entry >>> D {'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']}
15,dictionary的values()方法返回dictionary的全部values
>>> D = {'spam': 2, 'ham': 1, 'eggs': 3} >>> list(D.values()) #能夠不用list()方法,由於D.values()的值原本就是list [3, 2, 1]
16,dictionary的items()方法返回dictionary的全部key=value tuple,返回的是一個list。
>>> list(D.items()) [('eggs', 3), ('spam', 2), ('ham', 1)]
17,有時候不肯定dictionary是否有某個key,而若是仍然有以前的index方法來獲取,可能引發程序error退出。使用get方法能夠避免這樣的錯誤致使程序出現error。
若是沒有某個key,get會返回None,而若是不想讓程序提示None,能夠在第二個參數填入想要輸出的內容,以下:
>>> D.get('spam') # A key that is there 2 >>> print(D.get('toast')) # A key that is missing None >>> D.get('toast', 88) 88
18,dictionary有一個update方法,能夠將一個dictionary加入到另一個dictionary中,將D2加入到D中。應該注意的是,若是它們有相同的keys,那麼D中重複的key所對應的值將被D2的key所對應的值覆蓋。
>>> D {'eggs': 3, 'spam': 2, 'ham': 1} >>> D2 = {'toast':4, 'muffin':5} # Lots of delicious scrambled order here >>> D.update(D2) >>> D {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1}
19,dictionary的pop方法,填入的參數是key,返回的值是value,被pop執行的entry被移除出dictionary。
20,如何遍歷一個dictionary? 能夠用for-in loop:
方法一: for key in D
方法二: for key in D.keys()
21, 若是想要根據value來得到key,能夠參考下面的例子:
D = {'spam': 2, 'ham': 1, 'egg': 3} E = {'spam': 4, 'toast': 3, 'hamburger': 5} D.update(E) #print D some_food = [key for (key, value) in D.items() if value == 3] print some_food
如上面斜體的表達式,將返回list。若是這個value對應多個key,則返回的list將有多個item,若是僅有一個key,那麼這個list將只有一個值,此時能夠用list[0]來將中括號去除。
22,做爲key的值得類型能夠是string、integer、float、tuple等不會改變的值, 用戶本身定義的object也能做爲key,只要它們是hashable而且不會改變的。像list、set、dictionary等這些會變的type不能做爲dictionary的key。
23,下面這個例子闡述了tuple類型的key在座標問題中的做用:
>>> Matrix = {} >>> Matrix[(2, 3, 4)] = 88 >>> Matrix[(7, 8, 9)] = 99 >>> >>> X = 2; Y = 3; Z = 4 # ; separates statements: see Chapter 10 >>> Matrix[(X, Y, Z)] 88 >>> Matrix {(2, 3, 4): 88, (7, 8, 9): 99}
24,建立dictionary的幾個方法:
方法一:傳統的方法
{'name': 'Bob', 'age': 40} # Traditional literal expression
方法二:逐一賦值
D = {} # Assign by keys dynamically D['name'] = 'Bob' D['age'] = 40
方法三:經過dict函數建立,注意,使用這種方法,key只能是string
dict(name='Bob', age=40) # dict keyword argument form
方法四:將key/value做爲一個tuple,再用[]括起來,寫進dict()中,這種比較少用到
dict([('name', 'Bob'), ('age', 40)]) # dict key/value tuples form
方法五:使用zip()函數
dict(zip(keyslist, valueslist)) # Zipped key/value tuples form (ahead)
方法六:使用fromkeys函數,不多用到
>>> dict.fromkeys(['a', 'b'], 0) {'a': 0, 'b': 0}
25,使用dictionary comprehensions來建立dictionary的例子:
25.1 別忘了冒號。。
>>> D = {x: x ** 2 for x in [1, 2, 3, 4]} # Or: range(1, 5) >>> D {1: 1, 2: 4, 3: 9, 4: 16}
25.2
>>> D = {c: c * 4 for c in 'SPAM'} # Loop over any iterable >>> D {'S': 'SSSS', 'P': 'PPPP', 'A': 'AAAA', 'M': 'MMMM'}
25.3
>>> D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS', 'HAM']} >>> D {'eggs': 'EGGS!', 'spam': 'SPAM!', 'ham': 'HAM!'}
25.4
>>> D = {k:0 for k in ['a', 'b', 'c']} # Same, but with a comprehension >>> D {'b': 0, 'c': 0, 'a': 0}
26,在Python 3.x中,dictionary的keys()方法返回的再也不是list。而是相似像set同樣的結構。不過能夠使用list()強迫它們組成一個list。
>>> D = dict(a=1, b=2, c=3) >>> D {'b': 2, 'c': 3, 'a': 1} >>> K = D.keys() # Makes a view object in 3.X, not a list >>> K dict_keys(['b', 'c', 'a']) >>> list(K) # Force a real list in 3.X if needed ['b', 'c', 'a']
它們具備交集、並集、等set所具備的運算:
>>> D = {'a': 1, 'b': 2, 'c': 3} >>> D.keys() & D.keys() # Intersect keys views {'b', 'c', 'a'} >>> D.keys() & {'b'} # Intersect keys and set {'b'} >>> D.keys() & {'b': 1} # Intersect keys and dict {'b'}
27,練習題:用兩種方法建立一個list,這個list包含5個0:方法一:[0,0,0,0,0]方法二:[0 for i in range(5)]方法三:[0] * 5方法四:用循環加append的方法