python基礎 -- 內建函數

1.lambdapython

# 匿名函數
# 基本用法 lambda x: x**2
    # 第一個參數,而後是表達式
# 也能夠使用以下
(lambda x: x**2)(5)

2. map()app

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()函數

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()rest

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, ... ]


    最近總有些煩心事,唉。人生不免會有所迷茫,堅決信念一直走下去~code

    好在最近,找了一條能夠來回坐始發站的地鐵,這樣來回大約有50分鐘x2 的時間能夠看書,感受好充實呀。ci

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

相關文章
相關標籤/搜索