Anonymous lambda functions and built-in functions (sorted, filter, map, reduce)

'' ' Anonymous function
lambda Parameters: Return Value

Is generally used together with the built-in functions (sorted, map, filter, reduce)

sorted(Iterable, key=None,reverse=False)
    key is the key, collation, sorted will automatically iterables each passed to the key.
    And sorted according to the content key returned.
    
map(function, iterable)
    Can be mapped iterables each element, respectively, executed function
    
filter(function, iterable)
    function: function for screening, the filter will automatically pass iterable the elements to function.
    According to function and then returned True or False to determine whether to keep this data.

reduce(function, iterable, initial)
    The reduce function will automatically iterables out each pass to a function
    The first two values ​​passed in, and the return value and continue to the next element as a function of the parameters passed to the function
    So, function calculation result finally obtained.

'''
lst = [1, 5, 3, 4, 6]
lst2 = the sorted (LST)
 Print (LST)   # [. 1,. 5,. 3,. 4,. 6] 
Print (lst2)   # [. 1,. 3,. 4,. 5,. 6] 

DIC = {. 1: " A " ,. 3: " C " , 2: " B " }
 Print (the sorted (DIC))   # If the dictionary, then the return key after the sort the results: [1, 2, 3]
lst = ["apple", "banana", "peach", "pear", "watermelon"]
lst2 = the sorted (LST, Key = the lambda S: len (S))   # calculates the string length of the sort 
Print (lst2)   # [ 'PEAR', 'Apple', 'Peach', 'Banana', 'Watermelon']
lst = [{"id": 1, "name": "lily", "age": 18},
      {"id": 2, "name": "lucy", "age": 20},
      {"id": 3, "name": "tom", "age": 19}]
lst2 = sorted(lst, key=lambda dic: dic["age"])  # 根据年龄排序
print(lst2)  # [{'id': 1, 'name': 'lily', 'age': 18}, {'id': 3, 'name': 'tom', 'age': 19}, {'id': 2, 'name': 'lucy', 'age': 20}]

 

Guess you like

Origin www.cnblogs.com/lilyxiaoyy/p/11899417.html