程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Map, reduce, filter and other functions often used with lambda [Python]

編輯:Python

Python Zhongchanghe lambda Functions used with :map、reduce、filter etc.


lambda Keywords can be used to create small anonymous functions .
It consists of parameters and a separate expression constitute , The expression will be evaluated at call time . establish lambda The syntax of the function is lambda [parameters]: expression.

lambda Often with built-in or functools Use with some functions of :

  • map(function, iterable, ):
    take function The function acts on iterable On every element in , And output the result of the iterator .
    If more than one is passed in iterable Parameters , So ask function There should be the same number of input parameters , To multiple iterable Perform operations at the same time .
    If the length of multiple iteratible objects passed in is different , Then the shortest iteratible object traversal ends , The whole iteration stops .

    foo = map(lambda x: x ** 2, [1, 3, 5, 7, 9])
    print(type(foo)) # <class 'map'>
    for _ in foo:
    print(_, end=' ') # 1 9 25 49 81 
    l1 = list(range(1, 6))
    l2 = list(range(1, 5)) # Take the short iteratible object as the generation times 
    bar = map(lambda x, y: x ** y, l1, l2) # x, y The two parameters correspond to l1,l2 Two iteratible objects 
    while True:
    try:
    print(bar.__next__(), end=' ') # 1 4 27 256
    except StopIteration:
    break
    

    For the case that the input of the function is already a parameter tuple , see also itertools.starmap().

    from itertools import starmap
    l1 = list(range(1, 6))
    l2 = list(range(1, 5))
    baz = starmap(pow, zip(l1, l2)) # Yes [(1,1),(2,2),(3,3),(4,4)] Execution one by one pow()
    for _ in baz:
    print(_, end=' ') # 1 4 27 256
    
  • filter(function, iterable):
    return iterable In the implementation of function The result is True The elements of , The output is an iterator . If function yes None, It will be assumed that it is an identity function , That is to iterable The elements in Treu/False Judge .filter(function, iterable) Equivalent to a generator expression , When function No None For the time being (item for item in iterable if function(item));function yes None For the time being (item for item in iterable if item) .

    l = [1, 8, 9, 5, 0, 34, 78, 43, 90, 0]
    foo = filter(lambda x: x > 40, l)
    print(list(foo)) # [78, 43, 90]
    bar = filter(None, l)
    print(list(bar)) # [1, 8, 9, 5, 34, 78, 43, 90]
    

    If you want to let iterable The element of is judged as False Only return when , have access to itertools.filterfalse() .

    foo = itertools.filterfalse(lambda x: x % 2, l)
    print(list(foo))
    bar = itertools.filterfalse(None, l) # [8, 0, 34, 78, 90, 0]
    print(list(bar)) # [0, 0]
    
  • functools.reduce(function, iterable[, initializer]):
    Two parameters of function Apply cumulatively from left to right to iterable The elements of , Reduce iteratible objects to a single value . for example ,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) It's calculation ((((1+2)+3)+4)+5) Value .
    Parameters on the left x Is the accumulated value, and the parameter on the right y It's from iterable The update value of . If there are options initializer, It will be placed before the entry of the iteratable object involved in the calculation , It is used as the default value when the iteratable object is empty . If not given initializer also iterable Contains only one element , The first item... Will be returned .

    from functools import reduce
    l = [1, 2, 3, 4, 5]
    foo = reduce(lambda x, y: x * y, l)
    print(foo) # 120 = 1 * 2 * 3 * 4 * 5
    bar = reduce(lambda x, y: x * y, l, 0)
    print(bar) # 0 = 0 * 1 * 2 * 3 * 4 * 5
    baz = reduce(lambda x, y: x * y, [1])
    print(baz) # 1
    
  • In order of key:

    pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
    pairs.sort(key=lambda pair: pair[1])
    print(pairs) # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
    # perhaps 
    pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
    pairs = sorted(pairs, key=lambda pair: len(pair[1]))
    print(pairs) # [(1, 'one'), (2, 'two'), (4, 'four'), (3, 'three')]
    

Reference resources

builtin Built in functions :https://docs.python.org/zh-cn/3/library/functions.html
itertools iterator function :https://docs.python.org/zh-cn/3/library/itertools.html
functools Higher order function :https://docs.python.org/zh-cn/3/library/functools.html


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved