Python學習筆記二(高級特性)

      學習完Python學習筆記一(基礎知識),下面學習Python的高級特性

     1. 切片         

#取一個list或tuple的部分元素是非常常見的操作,即輸出第0,1,2三個元素
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

# 方法一:
print([L[0], L[1], L[2]])

# 方法二:
r = []
n = 3
for i in range(n):
    r.append(L[i])

print(r)

# 方法三:
print(L[0:3])
#如果第一個索引是0,還可以省略:
print(L[:3])

print(L[2:3])

    輸出結果:
     
['Michael', 'Sarah', 'Tracy']
['Michael', 'Sarah', 'Tracy']
['Michael', 'Sarah', 'Tracy']
['Michael', 'Sarah', 'Tracy']
['Tracy']

2.迭代

  類似於java的for...each方法,任何可迭代對象都可以作用於for循環,包括我們自定義的數據類型,只要符合迭代條件(即Iterable類型的對象),就可以使用for循環。
 
print("#dict遍歷")
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
    print(key)

print("#字符串遍歷")
for ch in 'ABC':
    print(ch)

print("#輸出下標值")
for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)

print("同時遍歷兩個元素")
for x, y in [(1, 1), (2, 4), (3, 9)]:
    print(x, y)

    輸出結果:
   
#dict遍歷
a
b
c
#字符串遍歷
A
B
C
#輸出下標值
0 A
1 B
2 C
同時遍歷兩個元素
1 1
2 4
3 9

  3.列表生成式  

print("#列表生成式")
print([x * x for x in range(1, 11)])
   輸出結果: 
#列表生成式
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

  4.生成器

    通過列表生成式,我們可以直接創建一個列表。但是,受到內存限制,列表容量肯定是有限的。而且,創建一個包含100萬個元素的列表,不僅佔用很大的存儲空間,如果我們僅僅需要訪問前面幾個元素,那後面絕大多數元素佔用的空間都白白浪費了。

print("#生成器")
g = (x * x for x in range(10))

print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))

print("for循環遍歷")
g = (x * x for x in range(10))
for n in g:
    print(n)

輸出結果:
 
#生成器
0
1
4
9
16
for循環遍歷
0
1
4
9
16
25
36
49
64
81


5.迭代總結 

凡是可作用於for循環的對象都是Iterable類型;

凡是可作用於next()函數的對象都是Iterator類型,它們表示一個惰性計算的序列;

集合數據類型如listdictstr等是Iterable但不是Iterator,不過可以通過iter()函數獲得一個Iterator對象;

Python的for循環本質上就是通過不斷調用next()函數實現的。

6. 函數式編程

    函數式編程就是一種抽象程度很高的編程範式,純粹的函數式編程語言編寫的函數沒有變量,因此,任意一個函數,只要輸入是確定的,輸出就是確定的,這種純函數我們稱之爲沒有副作用。而允許使用變量的程序設計語言,由於函數內部的變量狀態不確定,同樣的輸入,可能得到不同的輸出,因此,這種函數是有副作用的。允許把函數本身作爲參數傳入另一個函數,還允許返回一個函數,即函數本身也可以賦值給變量,即:變量可以指向函數。

 
print("#函數爲變量")
f = abs
print(f(-10))

print("#函數作爲參數傳入")
def add(x, y, f):
    return f(x) + f(y)

print(add(-5, 6, abs))

  輸出結果:
#函數爲變量
10
#函數作爲參數傳入
11

7.map/reduce   

print("#map/reduce")
def f(x):
  return x * x

r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

#r是一個Iterator,Iterator是惰性序列,因此通過list()函數讓它把整個序列都計算出來並返回一個list
print(list(r))

   輸出結果: 
#map/reduce
[1, 4, 9, 16, 25, 36, 49, 64, 81]

 8.filter

   filter()的作用是從一個序列中篩出符合條件的元素。由於filter()使用了惰性計算,所以只有在取filter()結果的時候,纔會真正篩選並每次返回下一個篩出的元素。
print("#去除空字符串")
def not_empty(s):
    return s and s.strip()

r = filter(not_empty, ['A', '', 'B', None, 'C', '  '])

print(list(r))

   輸出結果:
  
#去除空字符串
['A', 'B', 'C']

  9.排序

print("#python排序")

r = sorted([36, 5, -12, 9, -21])
print(r)

print("#根據abs結果排序")
r = sorted([36, 5, -12, 9, -21], key=abs)
print(r)

print("#字符串排序")
#默認情況下,對字符串排序,是按照ASCII的大小比較的,由於'Z' < 'a',結果,大寫字母Z會排在小寫字母a的前面
r= sorted(['bob', 'about', 'Zoo', 'Credit'])
print(r)

print("#不區分大小寫字符串排序")
r= sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
print(r)

  輸出結果: 
#python排序
[-21, -12, 5, 9, 36]
#根據abs結果排序
[5, 9, -12, -21, 36]
#字符串排序
['Credit', 'Zoo', 'about', 'bob']
#不區分大小寫字符串排序
['about', 'bob', 'Credit', 'Zoo']

   10.匿名函數

  
print("#匿名函數")
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
 輸出結果:
 
#匿名函數
[1, 4, 9, 16, 25, 36, 49, 64, 81]

   11.裝飾器

         python裝飾器自己的理解非常類似於java的aop攔截器
    
import time
def now():
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))


f = now
print("打印當前時間")
f()
print("輸出函數名稱")
print(now.__name__)


# wrapper()函數的參數定義是(*args, **kw),因此,wrapper()函數可以接受任意參數的調用

def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper

# 在wrapper()函數內,首先打印日誌,再緊接着調用原始函數。
@log
def now():
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))

print("python裝飾功能測試驗證,相當於now=log(now)")
now()

# 傳入參數的log
def log(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator

@log("打印當前時間方法")
def now():
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))


print("python裝飾功能測試驗證,相當於now = log('execute')(now)")
now()

   輸出結果:
打印當前時間
2017-03-28 16:11:25
輸出函數名稱
now
python裝飾功能測試驗證,相當於now=log(now)
call now():
2017-03-28 16:11:25
python裝飾功能測試驗證,相當於now = log('execute')(now)
打印當前時間方法 now():
2017-03-28 16:11:25








    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章