zoukankan      html  css  js  c++  java
  • filter、map、sorted和reduce函数

    内置函数——filter、map和reduce

    filter

    filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

    例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:

    def is_odd(x):
        return x % 2 == 1

    然后,利用filter()过滤掉偶数:

    >>>list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))

    结果:

    [1, 7, 9, 17]

    利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:

    def is_not_empty(s):
        return s and len(s.strip()) > 0
    >>>list(filter(is_not_empty, ['test', None, '', 'str', '  ', 'END']))

    结果:

    ['test', 'str', 'END']

    注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。

    当rm为空时,默认删除空白符(包括' ', ' ', ' ', ' '),如下:

    >>> a = ' 123'
    >>> a.strip()
    '123'
    >>> a = '		123
    '
    >>> a.strip()
    '123'

    练习:

    请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:

    import math
    def is_sqr(x):
        return math.sqrt(x) % 1 == 0
    print(list(filter(is_sqr, range(1, 101))))

    #
    def is_sqr(x):
    return x**0.5 % 1 == 0
    print(list(filter(is_sqr, range(1, 101))))

    结果:

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    map

    Python中的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, 5, 6, 7, 8]
    def pow2(x):
        return x*x
    
    print(list(map(pow2, L)))
    
    Output:
    [1, 4, 9, 16, 25, 36, 49, 64]

    sorted

    对List、Dict进行排序,Python提供了两个方法
    对给定的List L进行排序,
    方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
    方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变

    sorted(iterable, key=None, reverse=False)

    参数说明:
    iterable:是可迭代类型;
    key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;
    reverse:排序规则. reverse = True  降序 或者 reverse = False 升序,有默认值。
    返回值:有序列表

    # 列表按照其中每一个值的绝对值排序
    l1 = [1,3,5,-2,-4,-6]
    l2 = sorted(l1,key=abs)
    print(l1)
    print(l2)
    
    #列表按照每一个元素的len排序
    l = [[1,2],[3,4,5,6],(7,),'123']
    print(sorted(l,key=len))

    reduce

    reduce() 函数会对参数序列中元素进行累积。

    函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

    reduce(function, iterable[, initializer])

    参数

    • function -- 函数,有两个参数
    • iterable -- 可迭代对象
    • initializer -- 可选,初始参数
    from functools import reduce
    
    def add(x,y):
        return x + y
    
    print (reduce(add, range(1, 101)))

    Output:
    5050
  • 相关阅读:
    [LeetCode] 582. Kill Process
    [LeetCode] 686. Repeated String Match
    [LeetCode] 341. Flatten Nested List Iterator
    [LeetCode] 404. Sum of Left Leaves
    [LeetCode] 366. Find Leaves of Binary Tree
    [LeetCode] 1485. Clone Binary Tree With Random Pointer
    [LeetCode] 459. Repeated Substring Pattern
    [LeetCode] 565. Array Nesting
    [LeetCode] 679. 24 Game
    [LeetCode] 364. Nested List Weight Sum II
  • 原文地址:https://www.cnblogs.com/Xuuuuuu/p/10165122.html
Copyright © 2011-2022 走看看