1、实现方法:
1.1准备数据
生成3个字典,每个字典有3到6个键(由序列中随机生成),并且,每个值为1到4(随机)
>>> from random import randint,sample #sample为在序列中随机产生>>> sample("ABCDEFG",3)['C', 'E', 'A']>>> s1 = {x:randint(1,4) for x in sample("ABCDEFG",randint(3,6))}>>> s1{ 'C': 3, 'B': 1, 'E': 1}>>> s2 = {x:randint(1,4) for x in sample('ABCDEFG',randint(3,6))}>>> s2{ 'A': 1, 'C': 2, 'B': 1, 'E': 3, 'D': 3}>>> s3 = {x:randint(1,4) for x in sample('ABCDEFG',randint(3,6))}>>> s3{ 'A': 2, 'C': 2, 'B': 1, 'E': 1, 'F': 4}
1.2查找具有公共键的组成字典或列表
两种方法:普通迭代法和使用集合交集的思想产生
方法一:普通迭代法
>>> for x in s1: if x in s2 and x in s3: resList.append(x)>>> resList['C', 'B', 'E']>>> for x in s1.iterkeys(): if x in s2.iterkeys() and x in s3.iterkeys(): res[x] = s1[x] >>> res{ 'C': 3, 'B': 1, 'E': 1}这里可以看出,对键的迭代,可以直接以字典对象迭代,如上例中生成列表的方式
方法二:使用集合交集的思想产生
>>> s1.viewkeys() & s2.viewkeys() &s3.viewkeys()set(['C', 'B', 'E'])
几个字典可以采用此方法,简单方便。如字典数量多,要采用map()函数和reduce()函数配合使用。
>>> map(dict.viewkeys,[s1,s2,s3])[dict_keys(['C', 'B', 'E']), dict_keys(['A', 'C', 'B', 'E', 'D']), dict_keys(['A', 'C', 'B', 'E', 'F'])]>>> reduce(lambda a,b:a &b, map(dict.viewkeys,[s1,s2,s3]))set(['C', 'B', 'E'])
2扩展知识:
2.1 sample()
>>> help(sample)Help on method sample in module random:sample(self, population, k) method of random.Random instance Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use xrange as an argument. This is especially fast and space efficient for sampling from alarge population: sample(xrange(10000000), 60)
随机采样:从已知序列中随机产生k个对象生成列表。
>>> sample("ABCDEFG",3)['C', 'E', 'A']
2.2 map()
>>> help(map)Help on built-in function map in module __builtin__:map(...) map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list ofthe items of the sequence (or a list of tuples if more than one sequence).
如本例中从三个字典组成的列表序列中,分别产生键列表map()返回的是一个大列表
>>> map(dict.viewkeys,[s1,s2,s3])[dict_keys(['C', 'B', 'E']), dict_keys(['A', 'C', 'B', 'E', 'D']), dict_keys(['A', 'C', 'B', 'E', 'F'])]>>> map(dict.viewkeys,[s1])[dict_keys(['C', 'B', 'E'])]>>> s1.viewkeys()dict_keys(['C', 'B', 'E'])
map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:
>>> def mysquare(x): return x*x>>> r = map(mysquare,[1,2,3,4,5,6,7,8,9])>>> r[1, 4, 9, 16, 25, 36, 49, 64, 81]>>> data = [1,3,5,7,9]>>> r = map(mysquare,data)>>> r[1, 9, 25, 49, 81]>>>
map()传入的第一个参数是f,即函数对象本身。
注意:在py3中map()返回的是一个迭代器,而不是一个列表。
由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
2.3 reduce()
>>> help(reduce)Help on built-in function reduce in module __builtin__:reduce(...) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when thesequence is empty.
>>> reduce(lambda a,b:a &b, map(dict.viewkeys,[s1,s2,s3]))
set(['C', 'B', 'E'])
此例和官方文档给出的例子,可以看出reduce()内建函数的用法
reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),我们就可以写出把str转换为int的函数:
>>> def char2num(s): return { '0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}[s]>>> def str2int(s): return reduce(lambda x,y: x*10+y, map(char2num,s) )>>> str2int("123456")123456>>>
记住这个算法吧,我相信会非常有用。
Lambda()函数,以前有介绍这里不再赘述。