专题7:详谈python的sort、sorted、map、filter、reduce 函数

sort()

  • 描述
    sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
  • 语法
    list.sort( key=None, reverse=False)
  • 参数
    • key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
    • reverse – 排序规则,reverse = True 降序, reverse = False 升序(默认)
l = [(2, 2), (3, 4), (4, 1), (1, 3)]
l.sort(key=lambda x: x[1], reverse=True) # 按照元祖的第二个元素排序(降序)
print(l)
# [(3, 4), (1, 3), (2, 2), (4, 1)]

sorted()

def sorted(*args, **kwargs): # real signature unknown
    """
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    pass
  • 对列表排序,返回的对象不会改变原列表
list = [1,5,7,2,4]
 
sorted(list)
Out[87]: [1, 2, 4, 5, 7]
#可以设定时候排序方式,默认从小到大,设定reverse = False 可以从大到小
sorted(list,reverse=False)
#Out[88]: [1, 2, 4, 5, 7]
sorted(list,reverse=True)
#Out[89]: [7, 5, 4, 2, 1]
  • 根据自定义规则来排序,使用参数:key
#使用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):
  return x + y;
reduce(c_sum, range(1,101)) #5050
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值