Python Cookbook学习记录 ch4_8-16_2013/11/2

4.8二维阵列变换

讲一个列表的列表,将行换成列,列换成行。可以使用列表推导式

>>> arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> newarr= [[row[col] for row in arr] for col in range(len(arr[0]))]
>>> print newarr
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

还有一种方法,使用内建函数zip

>>> print map(list,zip(*arr))
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

此方法让人比较迷惑,其实*arr将arr中的每一行作为元素传给zip函数,下面的两种方法是等效的

>>> print zip(*arr)
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9]
>>> d = [10,11,12]
>>> print zip(a,b,c,d)
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

*args是python用于接收或者传递任意基于位置的参数的语法,如果在函数的def语句中使用了星号语法,python将此标识符绑定到一个元组,元祖包含了所有基于位置接受的的参数。**kwds是python用于接收或者传递任意命名的参数的语法。当在函数的def的语句汇总使用了双星号语法,python会将标识符绑定到一个字典,字典中包含了所有接收到的命名参数。当定义或者调用函数时,必须确保*a和**k在所有参数之后,如果两者同时出现,要将**k放在*a之后

 

4.9从字典中取值

从字典中取值,但是又不想由于搜索的键不存在而处理异常

字典的get方法就是为取值而准备的:

>>> thedict = {'a':1,'b':2,'c':3}
>>> print thedict.get('d','not found')
not found
>>> print thedict.get('a','not found')
1

4.10 给字典增加一个条目

给定一个字典d,当k是字典的键,则直接使用d[k],若k不是d的键,则给字典增加一个新条目d[k]

setdefault方法正是为此设计的,setdefault的帮助文档如下:

>>> help(dict.setdefault)
Help on method_descriptor:

setdefault(...)
    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
>>> thedict = {'a':1,'b':2,'c':3}
>>> thedict.setdefault('a',4)
1
>>> print thedict
{'a': 1, 'c': 3, 'b': 2}
>>> thedict.setdefault('d',4)
4
>>> print thedict
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

文中举了一个例子,目的是创建一个单词到页数的映射,字典将每个某个词出现过得页都映射到一个列表中。例子将setdefault的第二个参数设定为一个空列表,然后通过append方法将“页数”添加到列表中

>>> def addword(theIndex,word,pagenumber):
    theIndex.setdefault(word,[]).append(pagenumber)

>>> pageindex = {'hello':[4,7,9],'world':[4,6,8]}
>>> addword(pageindex,'hello',10)
>>> print pageindex
{'world': [4, 6, 8], 'hello': [4, 7, 9, 10]}
>>> addword(pageindex,'haha',35)
>>> print pageindex
{'world': [4, 6, 8], 'haha': [35], 'hello': [4, 7, 9, 10]}

4.11 在无须过多援引的情况下创建字典

如下方法创建字典较花括号和冒号的方式简洁:

>>> data = dict(red=1,green=2,blue=3)
>>> print data
{'blue': 3, 'green': 2, 'red': 1}

如果键和值分别存在两个序列中,可以使用如下方法:

>>> the_keys = ['red','gerrn','blue']
>>> the_values = [1,2,3]
>>> d = dict(zip(the_keys,the_values))
>>> print d
{'blue': 3, 'red': 1, 'gerrn': 2}

4.12 将列表元素交替的作为键和值来创建字典

使用上一节提到的zip方法和切片方法

def dictFromList(keysAndValues):
    return dict(zip(keysAndValues[::2], keysAndValues[1::2]))

4.13 获取字典的一个子集

有一个巨大的字典,字典中有一些键属于一个特定的集合,创造一个包含这些键的集合及对应值的新字典

如果不想改动原字典:

def sub_dict(somedict, somekeys, default=None):
    return dict([ (k, somedict.get(k, default)) for k in somekeys ])

如果要删除这部分:

def sub_dict_remove(somedict, somekeys, default=None):
    return dict([ (k, somedict.pop(k, default)) for k in somekeys ])

4.14 反转字典

将各个值反映射到键

使用iteritem遍历所有键和值,并依次按照相反顺序存在序列中,最后使用dict方法生成一个新字典

iteritem方法的帮助文档如下:

>>> help(dict.iteritems)
Help on method_descriptor:

iteritems(...)
    D.iteritems() -> an iterator over the (key, value) items of D

实现如下:

>>> data = dict(red=1,green=2,blue=3)
>>> newdata = dict([(v,k) for k,v in data.iteritems()])
>>> print newdata
{1: 'red', 2: 'green', 3: 'blue'}

4.15 字典的一键多值

需要一个字典,能够将每个键映射都多个值上

如果使用list作为dict的值,可以使用4.10节使用到的setdefault方法,不过这种方法可以出现对应值得重复

>>> def addword(theIndex,word,pagenumber):
    theIndex.setdefault(word,[]).append(pagenumber)

>>> pageindex = {'hello':[4,7,9],'world':[4,6,8]}
>>> addword(pageindex,'hello',10)
>>> print pageindex
{'world': [4, 6, 8], 'hello': [4, 7, 9, 10]}
>>> addword(pageindex,'haha',35)
>>> print pageindex
{'world': [4, 6, 8], 'haha': [35], 'hello': [4, 7, 9, 10]}

如果使用子字典作为dict的值,这样就消灭了重复

d2 = {}
d2.setdefault(key, {})[value] = 1

在python 2.4中,上述无重复的方法可等价为如下方法:

d3 = {}
d3.setdefault(key, set()).add(value)

4.16 用字典分派方法和函数

字典可以以字符串或者其他对象为键,以被绑定的方法,函数作为值用于调用。这种方法可以替代case语句

animals = []
number_of_felines = 0
def deal_with_a_cat():
    global number_of_felines
    print "meow"
    animals.append('feline')
    number_of_felines += 1
def deal_with_a_dog():
    print "bark"
    animals.append('canine')
def deal_with_a_bear():
    print "watch out for the *HUG*!"
    animals.append('ursine')
tokenDict = {
    "cat": deal_with_a_cat,
    "dog": deal_with_a_dog,
    "bear": deal_with_a_bear,
    }
# Simulate, say, some words read from a file
words = ["cat", "bear", "cat", "dog"]
for word in words:
    # Look up the function to call for each word, and call it
    return tokenDict[word]()
nf = number_of_felines
print 'we met %d feline%s' % (nf, 's'[nf==1:])
print 'the animals we met were:', ' '.join(animals)

 

 

posted on 2013-11-03 20:56  七海之风  阅读(216)  评论(0)    收藏  举报

导航