python的函數語言程式設計

任平生78發表於2017-07-02

map

#對引數迭代器中的每個元素進行操作,返回一個新的迭代器
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables.  Stops when the shortest iterable is exhausted.
>>> l1=[1,3,5,7,9]
#求列表l1中的每個元素的平方
>>> l2=map(lambda x:x**2,l1)
>>> print(l2)
<map object at 0x7effe739d080>
>>> print(list(l2))
[1, 9, 25, 49, 81]

>>> l3=["python","php","mysql","linux"]
#把列表l3中每個元素變成大寫
>>> l4=map(lambda x:x.upper(),l3)
>>> print(l4)
<map object at 0x7effe739d0b8>
>>> print(list(l4))
[`PYTHON`, `PHP`, `MYSQL`, `LINUX`]

filter

#對迭代器的每個元素進行條件過濾,把符合條件的元素生成一個新的迭代器
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
>>> l3=["python","php","mysql","linux"]
#取得列表l3中以"p"開頭的元素
>>> l4=filter(lambda x:x.startswith("p"),l3)
>>> print(list(l4))
[`python`, `php`]

>>> l1=[99,88,77,66,55,44,33]
#求l1列表中大於55的元素
>>> l2=filter(lambda x:x>55,l1)
>>> print(list(l2))
[99, 88, 77, 66]

reduce

#在python3中,reduce需要匯入對應的模組才能使用
    from functools import reduce

#呼叫指定函式對引數列表中的每個元素從左到右進行累加操作
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.
>>> l1=[ i for i in range(101)]
>>> print(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
>>> sum1=reduce(lambda x,y:x+y,l1)
>>> print(sum1)
5050

>>> l1=["a","b","c","d"]
>>> sum=reduce(lambda x,y:x+y,l1)
>>> print(sum)
abcd


相關文章