学習ノート(9):第2章プログラム設計とデータ構造-Phothonの魔法機能、魅力的なところ、コード量を少なくする2...


今すぐ学習:https://edu.csdn.net/course/play/25504/304704?utm_source=blogtoedu
#      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('    ')