天天看點

python基礎4

python基礎4

高階函數

一個函數就可以接收另一個函數作為參數,這種函數就稱之為高階函數

sorted函數

排序也是在程式中經常用到的算法。 無論使用冒泡排序還是快速排序,排序的核心是比較兩個元素的大小。通正常定如下,實作從小到大的排序:

x < y, return -1

x == y, return 0

x > y, return 1

In [1]: t = (12,34,1,24,37)

In [2]: sorted(t)

Out[2]: [1, 12, 24, 34, 37]

In [4]: def reversed_cmp(x,y):###想要實作倒序,則需定義一個函數###

   ...:     if x>y :

   ...:         return -1

   ...:     elif x<y:

   ...:         return 1

   ...:     else:

   ...:         return 0

   ...:

In [5]: sorted(t,reversed_cmp)

Out[5]: [37, 34, 24, 12, 1]

In [6]: li = ['westos','redhat','linux']

In [7]: sorted(li)

Out[7]: ['linux', 'redhat', 'westos']###按字母的ASCII碼的順序

In [8]: li = ['linux','Redhat','westos']

In [9]: sorted(li)

Out[9]: ['Redhat', 'linux', 'westos']

In [10]: li = ['linux','Redhat','westos','redhat']

In [11]: sorted(li)

Out[11]: ['Redhat', 'linux', 'redhat', 'westos']

In [13]: def ignore_case_cmp(x,y):###既有大寫,又有小寫時,定義一個函數,忽略大小寫####

   ....:     lower1 = x.lower()

   ....:     lower2 = y.lower()

   ....:     if lower1 < lower2 :

   ....:         return -1

   ....:     elif lower1 > lower2:

   ....:         return 1

   ....:     else:

   ....:         return 0

   ....:

In [14]: sorted(li,ignore_case_cmp)

Out[14]: ['linux', 'Redhat', 'redhat', 'westos']

#函數作為傳回值()

def wrap_sum(*args):

    def my_sum():

        sum_num = 0

        for i in args:

            if not isinstance(i,(int,float)):

                print "Error Type"

            sum_num = sum_num +i

        return sum_num###傳回的函數名不加括号,就傳回該函數的位址###

    return my_sum

f = wrap_sum(1,2,3,6)

#print f

print f()###要想調該函數的值,則需要加括号####

f1 = wrap_sum(1,2,3,6)###傳遞的參數一樣,但是函數位址是不一樣的,每次調用都是調用一個新函數####

print f1

f2 = wrap_sum(1,2,3,6)

print f2

執行結果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py

12

<function my_sum at 0x8f0a28>

<function my_sum at 0x8f0aa0>

Process finished with exit code 0

def count():

    fs = []

    for i in range(1,4):

        def  f():

            return i*i

        fs.append(f)###将f的位址加入清單fs###

    return fs###傳回的是三個位址###

f1,f2,f3 = count()###調用count()函數,即将傳回的三個位址分别給了f1,f2,f3###

print f1()

print f2()

print f3()

###但是執行結果均為9###

改進:

        def f(j):

            def g():

                return j*j

            return g

        fs.append(f(i))

    return fs

f1,f2,f3 = count()

1

4

9

####匿名函數###

當我們在傳入函數時,有些時候,不需要顯式地定義函數,直接傳入匿名函數更友善。

關鍵字 lambda 表示匿名函數,冒号前面的 x 表示函數參數,冒号後表示要傳回的值

1 匿名函數不需要函數名,可以避免函數名的沖突

2 匿名函數可以跳過給函數配置設定棧空間

def pow1(x):

    return x*x

print map(pow1,range(1,11))

print map(lambda x:x*x,range(1,11))

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3 匿名函數可以指派給一個變量,需要運作時,變量名()

print lambda :1###列印了匿名函數的位址###

f = lambda :1###将位址指派給變量##

print f()###運作結果###

<function <lambda> at 0x13059b0>

###匿名函數傳遞必選參數和預設參數###

f = lambda x,y=2:x**y

print f(2,3)

print f(2)

8

###匿名函數傳遞可變參數###

f = lambda *x:map(lambda x:x*x,x)

print f(1,2,3,4)

[1, 4, 9, 16]

###匿名函數傳遞關鍵字參數###

f = lambda **kwargs:kwargs.items()

print f(name="fentiao",age=5)

[('age', 5), ('name', 'fentiao')]

練習:利用匿名函數和字典重新編輯電腦的代碼

x =input("num1:")

oper = raw_input("oper:")

y = input("num2:")

d ={

    "+":lambda x,y:x+y,

    "-":lambda x,y:x-y,

    "*":lambda x,y:x*y,

    "/":lambda x,y:x/y

}

if oper not in d.keys():

    print "Error"

print d[oper](x,y)

num1:3

oper:+

num2:4

7

In [2]: print 1 if 1>2 else 2###判斷1是否大與2,若大與則傳回1,小與則傳回2

2

####裝飾器####

用來裝飾函數的函數

1 不修改函數的源代碼

2 函數的調用方式沒有改變

###準備###

def hello():

    print "hello..."

    hello1()

def hello1():

    print "hello1..."

hello()

####計算程式執行時間###

import time###導入子產品###

def timmer(func):

    start_time = time.time()

    func()

    stop_time = time.time()

    return stop_time-start_time

def hello2():

    print "hello2..."

    time.sleep(2)###停2s###

print timmer(hello2)

###不改變調用方式###

import time

    def dec():

        start_time = time.time()

        func()

        stop_time = time.time()

        return stop_time-start_time

    return dec

    time.sleep(2)

hello2=timmer(hello2)

hello2()

hello2...

###裝飾器###

@timmer     ###相當于hello2=timmer(hello2),文法糖###

print hello2()

2.00218486786

###寫一個裝飾器實作hello2()函數的日志,日志内容為hello()的内容以及執行時間###

        return "%s run %f s"%(func.__name__,stop_time-start_time)

@timmer     ###hello2=timmer(hello2),文法糖

hello2 run 2.002128 s

###對檔案進行操作###

f = open("hello")###打開檔案###

print f.read()###讀檔案###

f.close()###關閉檔案###

f = open("hello",'w')###以寫方式打開,此時不能進行讀操作###

f.write("python")###會将檔案内容覆寫為”python“

其他的幾種模式:

r:可以讀取檔案内容,不可以寫入,如果檔案不存在則報錯

In [4]: f = open("/home/kiosk/PycharmProjects/pythonbasic/hello","r")

In [5]: f.read()

Out[5]: 'python'

In [6]: f.write

f.write       f.writelines  

In [6]: f.write("linux")###不可以寫入###

---------------------------------------------------------------------------

IOError                                   Traceback (most recent call last)

<ipython-input-6-18e05364d061> in <module>()

----> 1 f.write("linux")

IOError: File not open for writing

In [7]: f.write("linux")

r+:讀寫模式,依次覆寫源檔案内容,寫多少覆寫多少,如果檔案不存在則報錯

In [1]: f = open("hello","r+")

In [2]: f.read()

Out[2]: 'python'

In [3]: f.close()

In [4]: f = open("hello","r+")

In [5]: f.write("westos")

In [6]: f.read()###此時讀的是在覆寫後的下一個位置,是以要想讀取該檔案,則需要先關閉檔案,再打開###

Out[6]: ''

In [7]: f.close()

In [9]: f = open("hello","r+")

In [10]: f.read()

Out[10]: 'westos'

w:可以寫入檔案内容,不可以讀取,如果檔案不存在則建立

In [12]: f = open("lllll","w")

[kiosk@foundation38 pythonbasic]$ ls

10.py  12.py  14.py  1.py  3.py  5.py  7.py  9.py               hello  stack.py

11.py  13.py  15.py  2.py  4.py  6.py  8.py  file_operation.py  lllll  

w+:可讀寫,打開檔案使直接删除源檔案内容,如果檔案不存在則建立

In [13]: f = open('hello','w+')  

In [14]: f.read()

Out[14]: ''

In [17]: f.write("world")

In [18]: f.read()

Out[18]: ''

In [19]: f.close()

In [20]: f = open('hello')

In [21]: f.read()

Out[21]: 'world'

a:寫入,檔案末尾追加,不可以讀,檔案不存在則建立

In [22]: f = open('hello','a')

In [23]: f.write("hello,hello")

In [25]: f.close()

In [27]: f = open('hello')

In [28]: f.read()

Out[28]: 'worldhello,hello'

a+:讀寫,檔案追加,檔案不存在則建立

###指定讀取幾個位元組###

In [36]: f = open("hello")

In [37]: f.read(4)###讀取4個位元組###

Out[37]: 'worl'

###一行一行的讀取###

In [40]: f = open("hello")

In [41]: f.readlin

f.readline   f.readlines  

In [41]: f.readline()

Out[41]: 'worldhello,hello'

In [42]: f.readline()

Out[42]: ''

本文轉自blueclo51CTO部落格,原文連結:http://blog.51cto.com/12774272/1947896 ,如需轉載請自行聯系原作者