专题7 详谈python的sort、sorted、map、filter、reduce 函数_python map和sorted 为什么key的位置不同(1)

#使用key,默认搭配lambda函数使用
sorted(chars,key=lambda x:len(x))
#Out[92]: ['a', 'is', 'boy', 'bruce', 'handsome']
sorted(chars,key=lambda x:len(x),reverse= True)
#Out[93]: ['handsome', 'bruce', 'boy', 'is', 'a']

  • 根据自定义规则来排序,对元组构成的列表进行排序
tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
#key=lambda x: x[1]中可以任意选定x中可选的位置进行排序
sorted(tuple_list, key=lambda x: x[1]) 
#Out[94]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
sorted(tuple_list, key=lambda x: x[0])
#Out[95]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]
sorted(tuple_list, key=lambda x: x[2])
#Out[96]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]

map()

python的map 函数使得函数能直接以list的每个元素作为参数传递到funcname中, 并返回响应的新的list

#例: 返回某个list中的所有int数据
def sq(x):
  return x\*x #求x的平方
map(sq, [1,3, 5,7,9]) #[1, 9, 25, 49, 81]

map(lambda x:x\*\*2,[1,2,3,4])

filter()
  • filter(funcname, list)
filter(function or None, iterable) --> filter object
    
    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.

执行过程依次将list中的元素传递到funcname函数中, 根据funcname返回的True或False 保留或丢弃元素

from functools import reduce
#例: 返回某个list中的所有int数据
def is\_int(x):
  if isinstance(x, (int)):
    return True
  else:
    return False
 
 filter(is_int, ["Yi",2, "3", 4]) #[2, 4]

reduce()
  • reduce(funcname,list)
def reduce(function, sequence, initial=None): # real signature unknown; restored from \_\_doc\_\_
    """
 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 the
 sequence is empty.
 """
    pass

与map相比 , reduce类似于一个聚合类的应用方法, 把list中的参数, 依次传递给funcname, 每次funcname的参数都是上个funcname 执行结果和下一个list中的元素, 所以, funcname 的 参数必须是两个. 从执行过程看, 有点像递归

#例如: 求range(1, 101)(不包括101)的和,
def c\_sum(x, y):


**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值