博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2-5查找字典公共键
阅读量:4701 次
发布时间:2019-06-09

本文共 4734 字,大约阅读时间需要 15 分钟。

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}
randint sample

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'])
map reduce

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)
help(sample)

随机采样:从已知序列中随机产生k个对象生成列表。

>>> sample("ABCDEFG",3)['C', 'E', 'A']
View Code

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).
help(map)

如本例中从三个字典组成的列表序列中,分别产生键列表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'])
View Code

map()函数接收两个参数,一个是函数,一个是Iterablemap将传入的函数依次作用到序列的每个元素,并把结果作为新的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]>>>
f=x2 map实现

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.
help(reduce)

>>> 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>>>
def char2num(s)

记住这个算法吧,我相信会非常有用。

 

Lambda()函数,以前有介绍这里不再赘述。

 

 

转载于:https://www.cnblogs.com/smulngy/p/8691487.html

你可能感兴趣的文章
Spring事务
查看>>
java编程基础(三)流程控制语句
查看>>
让数据库跑的更快的7个MySQL优化建议
查看>>
jquery 取id模糊查询
查看>>
解决在vue中,自用mask模态框出来后,下层的元素依旧可以滑动的问题
查看>>
修改node节点名称
查看>>
PAT(B) 1014 福尔摩斯的约会(Java)
查看>>
PAT甲级题解-1123. Is It a Complete AVL Tree (30)-AVL树+满二叉树
查看>>
项目开发总结报告(GB8567——88)
查看>>
SSH加固
查看>>
端口扫描base
查看>>
iOS IM开发的一些开源、框架和教程等资料
查看>>
FansUnion:共同写博客计划终究还是“流产”了
查看>>
python 二维字典
查看>>
pip 警告!The default format will switch to columns in the future
查看>>
Arrays类学习笔记
查看>>
实验吧之【天下武功唯快不破】
查看>>
2019-3-25多线程的同步与互斥(互斥锁、条件变量、读写锁、自旋锁、信号量)...
查看>>
win7-64 mysql的安装
查看>>
dcm4chee 修改默认(0002,0013) ImplementationVersionName
查看>>