Chapter 8 Lists and Dictionaries
1, list的concatenation 和 repetition 操作:

>>> [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, 单一赋值:

>>> 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的个数不一致。

3,如何extend一个list?
方法一:使用slice assignment:

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

>>> L.extend([8, 9, 10]) # Insert all at end, named method
>>> L
[2, 3, 4, 1, 5, 6, 7, 8, 9, 10]

方法三:使用append方法

>>> L = ['eat', 'more', 'SPAM!']
>>> L.append('please') # Append method call: add item at end
>>> L
['eat', 'more', 'SPAM!', 'please']

4,sort()按升序或降序排列

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。

5,有一个sorted函数也可以做这样的事情,并返回一个list:

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


derek
10 声望3 粉丝

Learning Python