# 學習筆記（9):第二章 程序設計與數據結構-Python的魔法功能，魅力之所在，讓代碼量更少 2...

``````# 字典轉換成list
d = {'x': 'A', 'y' : 'B', 'z': 'C'}
print([k + '=' + v for k, v in d.items()])

# 生成list[1,2,3,..,10]
print(list(range(1, 11)))

# 生成list[1*1, 2*2, 3*3, ..., 10*10]
print([i * i for i in range(1, 11)])

# 'abc', '123' 輸出a1, a2, a3, b1, b2, b3
print([m + n for m in 'abc' for n in '123'])
# 也可同時加入if判斷
print([m + n for m in 'a.b.c' for n in '123' if m != '.'])

'''
生成器
'''
g = (i * i for i in range(1, 11))
print(g)
print(next(g))
for n in g:# for 底層調用next
print(n)

# yield關鍵字
def fib(max):
n,a,b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n += 1
return 'done'

fib(6)

# 輸出關鍵字換成yield,yield將函數包裝成generator
def fib(max):
n,a,b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n += 1
return 'done'

g = fib(6)
print(next(g))
for n in g:
print(n)

# try except方法輸出
while True:
try:
x = next(g)
print(x)
except StopIteration as e:
print('沒有數據了',e.value)
break

'''
迭代器
'''

# 判斷一個對象是否可迭代 Iterable
from _collections_abc import Iterable
print(isinstance([],Iterable))
print(isinstance({},Iterable))
print(isinstance('123',Iterable))
print(isinstance(123,Iterable))

# 判斷一個對象是否是迭代器Iterator
# python迭代器協議定義了兩個方法__next__和__iter__。生成器對象實現了這兩個方法，因此，從這方面來看，所有的生成器都是迭代器。
from _collections_abc import Iterator
print(isinstance([],Iterator))
print(isinstance({},Iterator))
print(isinstance('123',Iterator))
print(isinstance(123,Iterator))
print(isinstance(g,Iterator))

# iter()返回一個可迭代對象的迭代器
print(isinstance(iter([]),Iterator))
print(isinstance(iter({}),Iterator))
print(isinstance(iter('abc'),Iterator))

def triangles():
b=[1]
yield b
for i in range(4):
c=[]
for i,k in enumerate(b):
if(i>0):
c.append(k+b[i-1])
else:
c.append(k)
c.append(1)
b = c
yield b

n=0
result=[]
for t in triangles():
print(t)
result.append(t)
n+=1
if n==10:
break
if result==[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]:
print('測試通過')
else:
print('測試失敗')``````