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的方法