python方法整理

python

  1.   filter():用于过滤序列,返回符合条件的结果

        filter(function, iterable)

        def is_odd(n):

          return n % 2 == 1

        newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 

        lambda 一起使用:filter(lambda x: x % 2 == 0, range(10))

      

        

  2.        map() 会根据提供的函数对指定序列做映射    

      map(function, iterable, ...)

       >>>def square(x) :            # 计算平方数
      ...     return x ** 2
      ...
      >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
      [1, 4, 9, 16, 25]
      >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
      [1, 4, 9, 16, 25]
 
      # 提供了两个列表,对相同位置的列表数据进行相加
      >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
      [3, 7, 11, 15, 19]

  3.         sorted(iterable[, cmp[, key[, reverse]]]) 

    #sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

 

    #list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

    #reverse=True 降序,reverse=False 升序

    sorted(dict.items(),key=lambda x:x[1], reverse=True]]) 

    对dict的value 降序,返回结果

 

 

 

 

 

 

 

 

 

 

 


参考:https://www.runoob.com/python/python-func-map.html

posted @ 2020-07-29 18:02  liangxinxin  阅读(126)  评论(0编辑  收藏  举报