4个重要的内置函数

4个重要的内置函数


  1"""
  2Author: wangy325
  3Date: 2024-07-22 16:57:01
  4Description: 4个重要的函数
  5"""
  6
  7from functools import reduce
  8
  9# ############### #
 10#   filter()      #
 11#   map()         #
 12#   reduce()      #
 13#   zip()         #
 14# ############### #
 15
 16# Tips: 在命令行界面使用help()可以查看内置函数的帮助文档
 17# filter()函数
 18'''
 19class filter(object)
 20 |  filter(function or None, iterable) --> filter object
 21 |
 22 |  Return an iterator yielding those items of iterable for which function(item)
 23 |  is true. If function is None, return the items that are true
 24'''
 25
 26l1 = [1, 2, 3, 4]
 27f = filter(lambda x: x > 2, l1)
 28print(type(f))  # <class 'filter'>
 29
 30for e in f:
 31    print(e, end=', ')
 32print()
 33
 34for p in filter(lambda e: e.startswith('a'),
 35                ['apple', 'ass', 'pine', 'cindy', 'ark']):
 36    print(p, end=', ')
 37print()
 38
 39# map()函数
 40# 将2个容器里的元素一一对应运算,
 41# 直到少的那个容器所有元素都参与运算
 42# 这个*map*不是k-v映射哦
 43'''
 44class map(object)
 45 |  map(func, *iterables) --> map object
 46 |
 47 |  Make an iterator that computes the function using arguments from
 48 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 49'''
 50m = [2, 3, 4, 5, 6]
 51mm = map(lambda x, y: x + y, l1, m)
 52print(type(mm))  # <class 'map'>
 53for e in mm:
 54    print(e, end=", ")
 55print()
 56
 57# zip()函数
 58# 返回一个元组集
 59# 元素的数量取决于实参列表中元素最短长度
 60# 元组中元素的个数取决于实参的数量
 61'''
 62class zip(object)
 63 |  zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.
 64 |
 65 |     >>> list(zip('abcdefg', range(3), range(4)))
 66 |     [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
 67 |
 68 |  The zip object yields n-length tuples, where n is the number of iterables
 69 |  passed as positional arguments to zip().  The i-th element in every tuple
 70 |  comes from the i-th iterable argument to zip().  This continues until the
 71 |  shortest argument is exhausted.
 72 |
 73 |  If strict is true and one of the arguments is exhausted before the others,
 74 |  raise a ValueError.
 75'''
 76d = dict(zip('abc', ['va', 'vb', 'vc']))
 77for k, v in d.items():
 78    print(f'{k}: {v}')
 79
 80lz = list(zip('abcdefg', range(5), range(4)))
 81for t in lz:
 82    print(t, end=", ")
 83print()
 84
 85# reduce()函数
 86# 对可迭代参数的所有元素依次运算
 87# 返回运算后的值
 88# 可选一个初始值作为运算参数
 89'''
 90reduce(...)
 91    reduce(function, iterable[, initial]) -> value
 92
 93    Apply a function of two arguments cumulatively to the items of a sequence
 94    or iterable, from left to right, so as to reduce the iterable to a single
 95    value.  For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
 96    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
 97    of the iterable in the calculation, and serves as a default when the
 98    iterable is empty.
 99'''
100
101val = reduce(lambda x, y: x + y, ['p', 'p', 'l', 'e'], 'a')
102print(val)  # apple