python | Advanced functions | filter | map | reduce | sorted

filter(func, iterable)

  • Call the input function in a loop
  • Filter the incoming parameters. If the result of the function returns true, save it. If it returns false, don't. It also returns an iterator.
  • Remarks:
    • When the iterator is used up, throw it away until all are used up;
    • You can use list () to convert to a list; if it is not converted, it returns an iterator object, which can be called directly one by one using a for loop
# utils/core.py convert_legacy_filters_into_adhoc()
for
filt in filter(lambda x: x is not None, fd[filters]): fd['adhoc_filters'].append(to_adhoc(filt, 'SIMPLE', clause))

map(func, iterable)|reduce(func, iterable)

  • map will pass the passed function to each element of the sequence in turn and return the result as a new iterator
list(map(str, [1,2,3,4,5,6,7,8]))
  • reduce applies a function to a sequence, the function must accept two parameters
  • Each calculation result will continue to do cumulative calculation with the next element
# 等效写法
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

# exampl_1
from functionls import reduce
def add(x, y):
  return x + y

reduce(add, [1,3,5,7,9])

# exampl_2: Convert the sequence [1, 3, 5, 7, 9]to an integer 13579
def fn (x, y):
  return x * 10 + y
reduce (fn, [1,3,5,7,9])

# exampl_2: The string stris also a sequence, convert str to int
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn(x, y): return x * 10 + y def char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s))

def char2num(s):
    return DIGITS[s] #使用lambda简化内容 def str2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s))

sorted(iterable, key=func)

  • Add a key function to customize the sorting; the function specified by the key acts on each element of the list and reorders according to the returned results
# Sort by default ascending 
([36, 5, -12, 9, -21])
# Sort by absolute value
([36, 5, -12, 9, -21])  

# Sort by ASCII size by default, ' Z '<' a ', so' Z 'comes first
sorted(['bob', 'about', 'Zoo', 'Credit'])
# 实现忽略大小写的排序方法: 先将字符串全部转化为大写or小写
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
# 实现反向排序
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
# 实现L的按照名称排序
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
sorted(L, key=lambda x: x[0])

 

Guess you like

Origin www.cnblogs.com/bennyjane/p/12696939.html