python基础 -- 内建函数

2020-07-27 17:12:35 浏览数 (2)

1.lambda

代码语言:javascript复制
# 匿名函数
# 基本用法 lambda x: x**2
    # 第一个参数,然后是表达式
# 也可以使用如下
(lambda x: x**2)(5)

2. map()

代码语言:javascript复制
def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__
    """
    map(function, sequence[, sequence, ...]) -> list
    
    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).
    """
    return []

# 两个参数,一个处理函数,一个可迭代的序列
# 返回一个列表

# 例如 计算1到10的平方,并以列表的形式返回
map(lambda x: x**2, range(1, 11))
# 结果如下
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 当然 也可以如下这样使用
def square(x):
    return x**2

map(square, range(1, 11))

3.reduce()

代码语言:javascript复制
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x y, [1, 2, 3, 4, 5]) calculates
    ((((1 2) 3) 4) 5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    """
    pass

# 两个参数,一个接受两个参数的函数,一个序列参数
# 例如 计算 1到10 的和
reduce(lambda x, y: x y, range(1, 11))

# 当然,不适用lambda匿名函数也可以
def add(x, y):
    return x y
reduce(add, range(1, 11))

# 结果如下
45

4.filter()

代码语言:javascript复制
def filter(function_or_none, sequence): # known special case of filter
    """
    filter(function or None, sequence) -> list, tuple, or string
    
    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.
    """
    pass

# 接受两个参数,一个过滤函数,返回True 或者 False, 以及一个序列
# 例如, 计算100以内的偶数
filter(lambda x: x % 2 == 0, range(100))

# 如上
def div2(x):
    if x % 2 == 0:
        return True
    else:
        return False
filter(div2, range(100))

# 结果如下 
[0, 2, 4, 6, 8, 10, 12, 14, 16, ... ]

最近总有些烦心事,唉。人生难免会有所迷茫,坚定信念一直走下去~

好在最近,找了一条可以来回坐始发站的地铁,这样来回大约有50分钟x2 的时间可以看书,感觉好充实呀。

-- 2014-11-20 23:01:59

0 人点赞