學習完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.迭代
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.生成器
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類型,它們表示一個惰性計算的序列;
集合數據類型如list、dict、str等是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
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.裝飾器
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