Python3基礎-高階用法
阿新 • • 發佈:2018-11-25
寫在前面:本文主要是python高階練習部分,介紹了一些高階用法,這些都是零散的小知識,這些可以與函數語言程式設計合在一起使用。
函數語言程式設計1:Python中提供的函數語言程式設計主要有:
- map(函式,可迭代式)對映函式
- filter(函式,可迭代式)過濾函式
- reduce(函式,可迭代式)規約函式
- lambda函式
- 列表推導式
- zip()函式
generator 生成
詞彙
generator 英[ˈdʒenəreɪtə(r)] 美[ˈdʒɛnəˌretɚ]
n. 發電機,發生器; 電力公司; 生產者,創始者; [樂] 基礎低音
My understanding
關於生成器的基本概念,我沒有詳述,因為有關它的描述,網上一搜,一大把,在我看來,學習最有效的方法就是自己執行案例,通過案例反映生成器的作用。
比如,【點這裡】,哈哈這也是總結的。
案例1:元組推導式自動生成 generator
s = (x * x for x in range(5))
print(s)
<generator object <genexpr> at 0x000001343C239F10>
for x in s:
print(x, end=',')
0,1,4,9,16,
案例2:Fibonacci sequence
def fib(maximum): n, a, b = 0, 0, 1 while n < maximum: yield b a, b = b, a+b n += 1 return 'done' f = fib(10) print('fib(10)', f)
fib(10) <generator object fib at 0x000001343C239E08>
for x in f:
print(x, end=' ')
1 1 2 3 5 8 13 21 34 55
g = fib(5)
while 1:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
g: 1 g: 1 g: 2 g: 3 g: 5 Generator return value: done
iter 迭代
其實,迭代有可迭代的與迭代器,一個是形容詞,一個是名詞,所以他們是與區別的。
如果要使用需要匯入from collections import Iterable, Iterator
案例1:可迭代的
from collections import Iterable, Iterator
def g():
yield 1
yield 2
yield 3
print('Iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable))
print('Iterable? \'abc\':', isinstance('abc', Iterable))
print('Iterable? 123:', isinstance(123, Iterable))
print('Iterable? g():', isinstance(g(), Iterable))
Iterable? [1, 2, 3]: True
Iterable? 'abc': True
Iterable? 123: False
Iterable? g(): True
綜上:
- 列表是可迭代的
- 字串是可迭代的
- 數字是不可迭代的的
- 自定義的g()函式是可迭代的
案例2:迭代器
如果我們使用iter()
函式作用,可將列表and元組轉化為迭代器。
print('Iterator? [1, 2, 3]:', isinstance([1, 2, 3], Iterator))
print('Iterator? iter([1, 2, 3]):', isinstance(iter([1, 2, 3]), Iterator))
print('Iterator? \'abc\':', isinstance('abc', Iterator))
print('Iterator? 123:', isinstance(123, Iterator))
print('Iterator? g():', isinstance(g(), Iterator))
print('Iterator? (1, 2, 3):', isinstance((1, 2, 3), Iterator))
print('Iterator? iter((1, 2, 3)):', isinstance(iter((1, 2, 3)), Iterator))
Iterator? [1, 2, 3]: False
Iterator? iter([1, 2, 3]): True
Iterator? 'abc': False
Iterator? 123: False
Iterator? g(): True
Iterator? (1, 2, 3): False
Iterator? iter((1, 2, 3)): True
綜上:
- 列表 not is 迭代器
- 採用iter()轉化的列表 is 迭代器
- 字串not is 迭代器
- 數字not is 迭代器
- 自定義的g()函式is 迭代器
- 元組 not is 迭代器
- 採用iter()轉化的元組 is 迭代器
案例3:迭代元素
例子1
print('for x in [1, 2, 3, 4, 5]:')
for x in [1, 2, 3, 4, 5]:
print(x)
for x in [1, 2, 3, 4, 5]:
1
2
3
4
5
例子2
print('for x in iter([1, 2, 3, 4, 5]):')
for x in iter([1, 2, 3, 4, 5]):
print(x)
for x in iter([1, 2, 3, 4, 5]):
1
2
3
4
5
例子3
print('next():')
it = iter([1, 2, 3, 4, 5])
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
next():
1
2
3
4
5
案例4:字典迭代
想知道,字典的情況【點我】
構造字典
key = 'a', 'b', 'c'
value = 1, 2, 3
d = dict(zip(key, value))
迭代字典的鍵
print('iter key:', d)
for k in d.keys():
print('key:', k)
iter key: {'a': 1, 'b': 2, 'c': 3}
key: a
key: b
key: c
迭代字典的值
print('iter value:', d)
for v in d.values():
print('value:', v)
iter value: {'a': 1, 'b': 2, 'c': 3}
value: 1
value: 2
value: 3
迭代字典的鍵值對
print('iter item:', d)
for k, v in d.items():
print('item:', k, v)
iter item: {'a': 1, 'b': 2, 'c': 3}
item: a 1
item: b 2
item: c 3
列表迭代與推導
列表操作原理,【點我】
列表迭代
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
0 A
1 B
2 C
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)
1 1
2 4
3 9
列表推導式
print([x*x for x in range(1, 11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([x*x for x in range(1, 11) if x%2 == 0])
[4, 16, 36, 64, 100]
print([m + n for m in 'ABC' for n in 'XYZ'])
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
d = {'x':'A', 'y':'B', 'z':'C'}
print([k + '=' + v for k, v in d.items()])
['x=A', 'y=B', 'z=C']
L = ['Hello', 'World', 'Apple', 'IBM']
print([s.lower() for s in L])
['hello', 'world', 'apple', 'ibm']
切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
for i, value in enumerate(L):
print("L列表中元素的序:{}-->{}-->{}".format(i, value, i-len(L)))
L列表中元素的序:0-->Michael-->-5
L列表中元素的序:1-->Sarah-->-4
L列表中元素的序:2-->Tracy-->-3
L列表中元素的序:3-->Bob-->-2
L列表中元素的序:4-->Jack-->-1
print('L[0:3] =', L[0:3])
print('L[:3] =', L[:3])
print('L[1:3] =', L[1:3])
print('L[-2:] =', L[-2:])
L[0:3] = ['Michael', 'Sarah', 'Tracy']
L[:3] = ['Michael', 'Sarah', 'Tracy']
L[1:3] = ['Sarah', 'Tracy']
L[-2:] = ['Bob', 'Jack']
R = list(range(100))
print('R[:10] =', R[:10])
print('R[-10:] =', R[-10:])
print('R[10:20] =', R[10:20])
print('R[:10:2] =', R[:10:2])
print('R[::5] =', R[::5])
R[:10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
R[-10:] = [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
R[10:20] = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
R[:10:2] = [0, 2, 4, 6, 8]
R[::5] = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
關於yeild的例子
完整的程式碼
def each_ascii(s):
for ch in s:
yield ord(ch)
return '%s chars' % len(s)
def yield_from(s):
r = yield from each_ascii(s)
print(r)
def main():
for x in each_ascii('abc'):
print(x) # => 'a', 'b', 'c'
it = each_ascii('xyz')
try:
while True:
print(next(it)) # => 'x', 'y', 'z'
except StopIteration as s:
print(s.value) # => '3 chars'
# using yield from in main() will change main() from function to generator:
# r = yield from each_ascii('hello')
for ch in yield_from('hello'):
pass
main()
程式碼分析
def each_ascii(s):
for ch in s:
yield ord(ch)
return '%s chars' % len(s)
def yield_from(s):
r = yield from each_ascii(s)
print(r)
for x in each_ascii('abc'):
print(x)
97
98
99
it = each_ascii('xyz')
try:
while True:
print(next(it))
except StopIteration as s:
print(s.value)
120
121
122
3 chars
for ch in yield_from('hello'):
pass
5 chars
總結
有時候,對程式設計不感冒,但是把一個複雜的知識點多執行幾遍,太複雜了,把程式碼分成小程式碼執行,最後綜合理解,並整理成文。當然,這涉及到除錯程式碼部分,現在我還是個小菜鳥,除錯用的不太熟,當然程式碼量很大的時候可能要用到除錯部分。
End