带有key参数的函数filter,map,max,min
内置函数———filter
def is_not_empty(s):
return s and len(s.strip()) > 0
filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) 执行结果: ['test', 'str', 'END']
注意:
s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。 当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' '),如下: >>> a = ' 123'
>>> a.strip()
'123' >>> a = '\t\t123\r\n'
>>> a.strip()
'123'
map
map()函数应用于每一个可迭代的项,返回的是一个结果list。
如果有其他的可迭代参数传进来,map()函数则会把每一个参数都以相应的处理函数进行迭代处理。
map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
# 有一个list, L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以# 使用map函数处理。 >>> L = [1,2,3,4,]
>>> def pow2(x):
... return x*x
...
>>> map(pow2,L)
[1, 4, 9, 16]
内置函数——max
1. 函数功能为取传入的多个参数中的最大值,或者传入的可迭代对象元素中的最大值。默认数值型参数,取值大者;字符型参数,取字母表排序靠后者。还可以传入命名参数key,其为一个函数,用来指定取最大值的方法。default命名参数用来指定最大值不存在时返回的默认值。
2. 函数至少传入两个参数,但是有只传入一个参数的例外,此时参数必须为可迭代对象,返回的是可迭代对象中的最大元素。
>>> max(1) # 传入1个参数报错
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
max(1)
TypeError: 'int' object is not iterable
>>> max(1,2) # 传入2个参数 取2个中较大者
2
>>> max(1,2,3) # 传入3个参数 取3个中较大者
3
>>> max('1234') # 传入1个可迭代对象,取其最大元素值
'4'
3. 当传入参数为数据类型不一致时,传入的所有参数将进行隐式数据类型转换后再比较,如果不能进行隐式数据类型转换,则会报错。
>>> max(1,1.1,1.3E1) # 整数与浮点数可取最大值
13.0
>>> max(1,2,3,'3') # 数值与字符串不能取最大值
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
max(1,2,3,'3')
TypeError: unorderable types: str() > int() >>> max([1,2],[1,3]) # 列表与列表可取最大值
[1, 3]
>>> max([1,2],(1,3)) # 列表与元组不能取最大值
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
max([1,2],(1,3))
TypeError: unorderable types: tuple() > list()
. 当存在多个相同的最大值时,返回的是最先出现的那个最大值。
#定义a、b、c 3个列表
>>> a = [1,2]
>>> b = [1,1]
>>> c = [1,2] #查看a、b、c 的id
>>> id(a)
68128320
>>> id(b)
68128680
>>> id(c)
68128240 #取最大值
>>> d = max(a,b,c)
>>> id(d)
68128320 #验证是否最大值是否是a
>>> id(a) == id(d)
True
默认数值型参数,取值大者;字符型参数,取字母表排序靠后者;序列型参数,则依次按索引位置的值进行比较取最大者。还可以通过传入命名参数key,指定取最大值方法。
>>> max(1,2) # 取数值大者
2
>>> max('a','b') # 取排序靠后者
'b'
>>> max('ab','ac','ad') # 依次按索引比较取较大者
'ad' >>> max(-1,0) # 数值默认去数值较大者
0
>>> max(-1,0,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1
key参数的另外一个作用是,不同类型对象本来不能比较取最大值的,传入适当的key函数,变得可以比较能取最大值了。
>>> max(1,2,'3') #数值和字符串不能取最大值
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
max(1,2,'3')
TypeError: unorderable types: str() > int()
>>> max(1,2,'3',key = int) # 指定key为转换函数后,可以取最大值
'3' >>> max((1,2),[1,1]) #元组和列表不能取最大值
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
max((1,2),[1,1])
TypeError: unorderable types: list() > tuple()
>>> max((1,2),[1,1],key = lambda x : x[1]) #指定key为返回序列索引1位置的元素后,可以取最大值
(1, 2)
当只传入的一个可迭代对象时,而且可迭代对象为空,则必须指定命名参数default,用来指定最大值不存在时,函数返回的默认值。
>>> max(()) #空可迭代对象不能取最大值
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
max(())
ValueError: max() arg is an empty sequence
>>> max((),default=0) #空可迭代对象,指定default参数为默认值
0
>>> max((),0) #默认值必须使用命名参数进行传参,否则将被认为是一个比较的元素
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
max((),0)
TypeError: unorderable types: int() > tuple()
内置函数:min 用法
源码
def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""
pass
基础用法

tes = min(1,2,4)
print(tes)
#可迭代对象
a = [1, 2, 3, 4, 5, 6]
tes = min(a)
print(tes)

key属性的使用
当key参数不为空时,就以key的函数对象为判断的标准。
如果我们想找出一组数中绝对值最小的数,就可以配合lamda先进行处理,再找出最小值
a = [-9, -8, 11, 23, -4, 6]
tes = min(a, key=lambda x: abs(x))
print(tes)
高级技巧:找出字典中值最小的那组数据
如果有一组商品,其名称和价格都存在一个字典中,可以用下面的方法快速找到价格最贵的那组商品:

prices = {
'A':123,
'B':450.1,
'C':12,
'E':444,
}
# 在对字典进行数据操作的时候,默认只会处理key,而不是value
# 先使用zip把字典的keys和values翻转过来,再用min取出值最小的那组数据
min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (450.1, 'B')

当字典中的value相同的时候,才会比较key:

prices = {
'A': 123,
'B': 123,
}
min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, 'B')
min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, 'A')

和max用法基本一致
带有key参数的函数filter,map,max,min的更多相关文章
- python四个带 key 参数的函数(max、min、map、filter)
四个带 key 参数的函数: max()点击查看详细 min()点击查看详细 map()点击查看详细 filter()点击查看详细 1)max(iterable, key) key:相当于对可迭代对象 ...
- 高阶函数 filter map reduce
const app=new Vue({ el:'#app', data:{ books:[{ id:1, name:"算法导论", data: '2006-1', price:39 ...
- python 装饰器 第六步:带有收集参数的函数的装饰器
#第六步:带有收集参数的函数的装饰器 #装饰器函数 def kuozhan(func): #内部函数(扩展之后的eat函数) def neweat(*w,**n): #以下三步就是扩展之后的功能,于是 ...
- Python内置函数filter, map, reduce
filter.map.reduce,都是对一个集合进行处理,filter很容易理解用于过滤,map用于映射,reduce用于归并. 是Python列表方法的三架马车. 1. filter函数的功能相当 ...
- Python 内置函数&filter()&map()&reduce()&sorted()
常用内置函数 Python 2.x 返回列表,Python 3.x 返回迭代器 在进行筛选或映射时,输出的结果是一个数组,需要list帮助. 如:print(list(map(lambda x:x+1 ...
- python关于list的三个内置函数filter(), map(), reduce()
''' Python --version :Python 2.7.11 Quote : https://docs.python.org/2/tutorial/datastructures.html#m ...
- C++ (带有默认参数的函数参数)缺省函数参数
缺省参数?在C++中,允许实参的个数与形参的个数不同.在声明函数原型时,为一个或者多个形参指定默认值,以后调用这个函数时,若省略某一个实参,c++则自动的以默认值作为相应参数的值. 实列说明:#inc ...
- 常用函数-filter、map、reduce、sorted
常用函数 filter map reduce sorted和列表自带sort 待续... 一.filter函数 1.说明 filter()函数接收一个函数 f 和一个可迭代对象,这个函数 f 的作用是 ...
- js高阶函数filter、map、reduce
// 高阶函数 filter/map/reduce // filter中的回调函数有一个要求:必须返回一个boolean值, // 当返回true时,函数内部会自动将这次回调的 n 加入到新的数组中 ...
随机推荐
- vue的开发环境搭建命令加图解
vue的开发环境的搭建 不管什么软件我们都要去官网下载安装,这是作为专业程序员的安全意识. 1.安装node.js 官方下载的页面:点击这里 大约展示的页面是这样子的!我们演示是windows 64位 ...
- Mobiscroll手机触屏日期选择器
最近在制作jquery mobile因要用到日历控件,突然发现Mobiscroll非常不错.于是摘下来记录. A Mobiscroll是一个用于触摸设备(Android phones.iPhon ...
- es进行聚合操作时提示Fielddata is disabled on text fields by default
在进行派粗前,先执行以下操作 { "properties": { "updatedate": { "type": "text&qu ...
- 时间同步Servname not supported for ai_socktype
rdate -s 129.7.1.66rdate: 129.7.1.66: Servname not supported for ai_socktype ntpdate 0.centos.pool.n ...
- 修改activeMQ端口号
原文:http://jingyan.baidu.com/article/3ea51489fba6a152e61bbacc.html 修改TCP 61616端口 打开您的mq安装目录 请看下图 如下图所 ...
- linux 端口占用查看 netstat -tunpl | grep 6379
端口占用查看 netstat -tunpl | grep 6379 netstat -luntpu|grep fdfs
- 【POI】解析xls报错:java.util.zip.ZipException: error in opening zip file
今天使用POI解析XLS,报错如下: Servlet.service() for servlet [rest] in context with path [/cetBrand] threw excep ...
- cas服务器源码阅读笔记,对标博客
对标源码阅读博客:http://www.cnblogs.com/jiuzhongguo/category/375405.html 在CAS中很多地方使用了策略模式,那么根据什么方式来确定使用哪种策略呢 ...
- #!/usr/bin/env在脚本中的作用
在linux的一些脚本,需在开头一行指定脚本的解释程序,如: #!/usr/bin/env bash #!/usr/bin/bash #!/usr/bin/env python 告诉操作系统执行这个 ...
- Swift 版本号非常好的卡片切换效果基于ZLSwipeableView(相似于[陌陌点点][探探])
这是我在简书的文章. http://www.jianshu.com/p/734962c9bbed