最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python語言中的重要函數(shù)對象用法小結(jié)

 更新時間:2024年09月30日 11:14:47   作者:盛者無名  
Python作為一種強大的編程語言,提供了多種高級函數(shù)對象,如lambda匿名函數(shù)、map()、reduce()函數(shù),以及迭代器和生成器的使用,本文給大家介紹Python語言中的重要函數(shù)對象用法,感興趣的朋友跟隨小編一起看看吧

高級函數(shù)對象

lambda函數(shù)

python使用lambda來創(chuàng)建匿名函數(shù)。所謂匿名函數(shù),就是不再使用像def語句這樣標準的形式定義函數(shù)。

lambda [arg1,[arg2,...argn]]:expression

使用lambda函數(shù)的語法定義函數(shù),需要注意以下兩點:

  • 冒號之前的arg1,arg2,…表示他們是這個函數(shù)的參數(shù)
  • 匿名函數(shù)不需要return來返回值,表達式本身的結(jié)果就是返回值

定義匿名函數(shù)

sayHello = lambda : print("hello,python")
sayHello()

使用lambda函數(shù)實現(xiàn)兩數(shù)相加

sum = lambda arg1,arg2 : arg1+arg2;
print('相加后的值:',sum(10,20))
print('相加后的值:',sum(20,20))

map()函數(shù)

map()函數(shù)是python內(nèi)置的高階函數(shù),會根據(jù)提供的函數(shù)對指定序列做映射,第一個參數(shù)function是個函數(shù)對序列中每個元素都調(diào)用function函數(shù),返回包含每次function函數(shù)返回值的新序列

map(function,iterable,...)
  • function: 是個函數(shù),通過函數(shù)依次作用在序列中的每個元素中。
  • iterable: 一個或多個序列,也被稱為可迭代對象。

對列表中每個元素平方

def fun(x):
    return x*x
result=map(fun,[1,2,3])
print(list(result))

對列表中每個元素加3

result=map(lambda x: x+3,[1,3,5,6])
print(list(result))

兩個列表的每個元素實現(xiàn)相加

result=map((lambda x,y:x+y),[1,2,3],[6,7,9])
print(list(result))

reduce()函數(shù)

reduce(function,iterable)
  • function: 接收函數(shù),必須有兩個參數(shù)
  • iterable: 一個或多個序列,序列也稱為迭代對象

使用reduce()函數(shù)對列表中的元素進行累加

from functools import reduce
def add(x,y):
    return x+y
data = [1,2,3,4]
r=reduce(add,data)
print(r)
from functools import reduce
data=[1,2,3,4]
fun=lambda x,y:x+y
r2=reduce(fun,data)
print(r2)

該計算相當于(((1+2)+3)+4)=10

迭代器

迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到所有元素被訪問完結(jié)束。迭代器只能往前不能后退。

使用迭代器

lst=[1,2,3,4]
it=iter(lst)
print(next(it))
print(next(it))
print(next(it))

自定義迭代器

對于要返回迭代器的類,迭代器對象被要求支持下面兩個魔法方法

(1)iter()返回迭代器本身。

(2)next()返回容器的下一個元素的值。

斐波那契數(shù)列

def fib(max):
    a,b=1,1
    idx=0
    ls=[]
    while True:
        if idx==max:
            return ls
        ls.append(a)
        a,b=b,a+b
        idx=idx+1
if __name__=="__main__":
    result = fib(5)
    print(result)

自定義迭代器實現(xiàn)斐波那契數(shù)列

class Fibs(object):
    def __init__(self,max):
        self.max=max
        self.a=0
        self.b=1
        self.idx=0
    def __iter__(self):
        return self
    def __next__(self):
        fib=self.a
        if self.idx==self.max:
            raise StopIteration
        self.idx=self.idx+1
        self.a,self.b=self.b,self.a+self.b
        return fib
if __name__=='__main__':
    fibs=Fibs(5)
    print(list(fibs))

生成器

生成器是迭代器的一種實現(xiàn)。生成器不會把結(jié)果保存在一個系列中,而是保存生成器的狀態(tài),在每次進行迭代時返回一個值,直到遇到StopIteration異常時結(jié)束。

生成器的好處是延遲計算,一次返回一個結(jié)果。它不會一次生成所有的結(jié)果,這對于處理大數(shù)據(jù)量會非常有用。

生成器函數(shù)

在函數(shù)中如果出現(xiàn)了yield關(guān)鍵字,那么該函數(shù)就不再是普通函數(shù),而是生成器函數(shù)。

使用yield語句而不是return語句返回結(jié)果。yield語句一次返回一個結(jié)果,在每個結(jié)果中間掛起函數(shù)的狀態(tài),以便下次從它離開的地方繼續(xù)執(zhí)行。

簡單的生成器函數(shù)

def mygen():
    print('gen() 1')
    yield 1
    print('gen() 2')
    yield 2
    print('gen() 3')
    yield 3
gen =mygen()
print(next(gen))
print(next(gen))
print(next(gen))

使用生成器函數(shù)生成一個含有n個奇數(shù)的生成器,使用for語句迭代輸出

def odd(max):
    n=1
    count = 0
    while True:
        yield n
        n+=2
        count=count+1
        if count == max:
            raise StopIteration
odd_num=odd(3)
for num in odd_num:
    print(num)

迭代器同樣的效果

class odd(object):
    def __init__(self,max):
        self.count=0
        self.max=max
        self.start=-1
    def __iter__(self):
        return self
    def __next__(self):
        self.start+=2
        self.count=self.count+1
        if self.count==self.max:
            raise StopIteration
        return self.start
odd_num=odd(3)
for num in odd_num:
    print(num)

使用生成器生成斐波那契數(shù)列

def Fibs(max):
    a,b=1,1
    count=0
    while True:
        if count == max:
            raise StopIteration
        yield a
        a,b=b,a+b
        count=count+1
if __name__=="__main__":
    fib=Fibs(5)
    for item in fib:
        print(item)

裝飾器

裝飾器本質(zhì)是一個python函數(shù),它可以讓其他函數(shù)在不需要做任何代碼變動的前提下增加額外的功能,裝飾器的返回值也是一個函數(shù)對象。

簡單的裝飾器

先定義兩個簡單的數(shù)學函數(shù)

def add(a,b):
    return a+b
def subtraction(a,b):
    return a-b
a=5
b=1
print('{0}+{1}={2}'.format(a,b,add(a,b)))
print('{0}-{1}={2}'.format(a,b,subtraction(a,b)))
def decorator(func):
    def inner(a,b):
        print('輸入?yún)?shù) a={0},b={1}'.format(a,b))
        f1=func(a,b)
        return f1
    return inner
@decorator
def add(a,b):
    return a+b
@decorator
def subtraction(a,b):
    return a-b
a=5
b=1
print('{0}+{1}={2}'.format(a,b,add(a,b)))
print('{0}-{1}={2}'.format(a,b,subtraction(a,b)))

使用裝飾器傳遞參數(shù)

def pre_str(pre=''):
    def decorator(func):
        def inner(a,b):
            print('裝飾器參數(shù) pre={0}'.format(pre))
            print('輸入?yún)?shù) a={0},b={1}'.format(a,b))
            f1=func(a,b)
            return f1
        return inner
    return decorator
@pre_str('add')
def add(a,b):
    return a+b
@pre_str('subtraction')
def subtraction(a,b):
    return a-b
a=5
b=1
print('{0}+{1}={2}'.format(a,b,add(a,b)))
print('{0}-{1}={2}'.format(a,b,subtraction(a,b)))

基于類的裝飾器

class Test():
    def __init__(self,func):
        self.func=func
    def __call__(self, *args, **kwargs):
        print('The current function:%s' % self.func.__name__)
        return self.func
@Test
def test1():
    print("Hello")
test1()

到此這篇關(guān)于Python語言中的重要函數(shù)對象用法的文章就介紹到這了,更多相關(guān)Python函數(shù)對象用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

永定县| 阳泉市| 峨眉山市| 浮梁县| 乌拉特前旗| 上杭县| 新巴尔虎右旗| 孙吴县| 凤庆县| 清河县| 沐川县| 南木林县| 望谟县| 迭部县| 东至县| 恩平市| 安顺市| 沅江市| 应用必备| 当涂县| 师宗县| 彭水| 泰宁县| 黑河市| 舟曲县| 华亭县| 府谷县| 关岭| 凤冈县| 德清县| 大姚县| 日照市| 林周县| 四子王旗| 定安县| 浏阳市| 宁安市| 大丰市| 桂平市| 潮安县| 凌源市|