day12_步入百萬年薪的第十二天——生成器、推導式、簡單內置函數

day12

生成器

迭代器:python中內置的一種節省空間的工具

生成器的本質就是一個迭代器

迭代器和生成器的區別:一個是pyhton自帶的,一個是程序員自己寫的

寫一個生成器
  • 基於函數

  • 在函數中將return改寫成yield就是一個生成器

  • 函數名()就是產生一個生成器

  • return 可以寫多個,但是只執行一個

  • yield也可以寫多個,還可以返回多次

    **一個__next__()對應一個yield**

    ______next______() == next():推薦使用next()

    ______iter______() == iter()

  • yield 也是返回,會記錄執行位置

  • 生成器可以使用for循環獲取

  • yield from——將可迭代對象元素逐一返回

  • 在函數的內部 yield 能將for循環和while循環進行臨時暫停

優點:節省空間——惰性機制

​ 不能逆行

​ 一次性

​ 一個next對應一個yield

def func():
    print(123)
    return '你好'
func()
---------------------------------
def func():
    if 3>2:
        yield '你好'
    if 4>2:
        yield '我好'
    yield '大家好'
g = func()   # 產生一個生成器
print(next(g))
print(next(g))
print(next(g))
for i in g:
    print(1)
while True:
    try:
        print(g.__next__())
    except StopIteration:
        break
---------------------------------        
def foo():
    for i in range(10):
        pass
    yield i
    count = 1
    while True:
        yield count
        count += 1 
g = foo()
# print(next(g))  # 推薦使用
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# for i in g:
#     print(i)
坑 —— 會產生新的生成器
print(next(foo()))
print(next(foo()))
send()
# def gen(name):
#     print(f'{name} ready to eat')
#     while 1:
#         food = yield
#         print(f'{name} start to eat {food}')
------------------------------------------------------
# dog = gen('alex')
# next(dog)
# next(dog)
# next(dog)
------------------------------------------------------
# def gen(name):
#     # print(f'{name} ready to eat')
#     while 1:
#         food = yield 222
#         print(f'{name} start to eat {food}')
# dog = gen('alex')
# next(dog)  # 第一次必須用next讓指針停留在第一個yield後面
# 與next一樣,可以獲取到yield的值
# ret = dog.send('骨頭')
# print(ret)
------------------------------------------------------
# def gen(name):
#     print(f'{name} ready to eat')
#     while 1:
#         food = yield
#         print(f'{name} start to eat {food}')
------------------------------------------------------
# dog = gen('alex')
# next(dog)
# # 還可以給上一個yield發送值
# # next(dog)
# dog.send('骨頭')
# dog.send('狗糧')
# dog.send('香腸')
生成器應用場景
def func():
    lst = []
    for i in range(10000):
        lst.append(i)
    return lst
print(func())
---------------------------------  
def func():
    for i in range(10000):
        yield i
g = func()
for i in range(50):
    print(next(g))
---------------------------------     
def func():
    lst = ["牛羊配","老奶奶花生米","衛龍","蝦扯蛋","米老頭","老乾媽"]
    for i in lst:
        yield i 
g = func()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
---------------------------------  
def func():
    lst = ["牛羊配","老奶奶花生米","衛龍","蝦扯蛋","米老頭","老乾媽"]
    lst2 = ["小浣熊","老乾爹","親嘴燒","麻辣燙","黃燜雞","井蓋"]
    yield from lst1
    yield from lst2
g = func()
print(next(g))
print(next(g))
print(next(g))
# for i in g:
#   print(i)

推導式

列表推導式:

循環推導式:[變量(加工后的變量) for循環]

篩選推導式:[變量(加工后的變量) for循環 加工條件]

# lst = []
# for i in range(20):
#     lst.append(i)
# print(lst)

# list推導式
# print([i for i in range(20)])
------------------------------------------------------
# 循環模式
# [變量 for i in range(20)]
# print([i+1 for i in range(10)])
------------------------------------------------------
# 篩選模式
# lst = []
# for i in range(20):
#     if i % 2 == 0:
#         lst.append(i)
# print(lst)

# print([i for i in range(20) if i % 2 == 0])
# [變量(加工后的變量) for循環 加工方式]

# print([i for i in range(50) if i % 2 == 1])
# print([i for i in range(1,50,2)])
------------------------------------------------------
list二層嵌套for:
# print([i for i in range(20) for n in range(10)])
lst = []
for i in range(20):
    for n in range(10):
        lst.append(i)
print(lst)
生成器推導式:

循環推導式:(變量(加工后的變量) for循環)

篩選推導式:(變量(加工后的變量) for循環 加工條件)

# 循環模式:
# g = (i for i in range(20))
# print(next(g))
# print(next(g))
# print(next(g))

# print(list((i for i in range(20))))
------------------------------------------------------
# 篩選模式
# g = (i for i in range(50) if i % 2 == 1)
# for i in g:
#     print(i)
------------------------------------------------------
二層for嵌套:
g = (i for i in range(20) for n in range(10))
for i in g:
    print(i)
集合推導式:set()

{鍵:值 for循環 加工條件}

# 集合推導式:(了解)
# print({i for i in range(10)})
# print({i for i in range(10) if i % 2 == 0})
------------------------------------------------------
二層for嵌套:(去重)
print({i*n for i in range(20) for n in range(10)})
print(len({i*n for i in range(20) for n in range(10)}))
字典推導式:{}

{變量(加工后的變量) for循環 加工條件}

# 字典推導式:(了解)
# print({i:i+1 for i in range(10)})
# print({i:i+1 for i in range(10) if i % 2 == 0})
# {鍵:值 for循環 加工條件}
------------------------------------------------------
二層for嵌套:
print({i:n for i in range(20) for n in range(10,20)})
dic = {}
for i in range(20):
    for n in range(20):
        dic[i] = n
print(dic)

內置函數一

eval():字符串裏面的計算公式得出答案

exec() :字符串裏面的代碼得出答案

工作和學習不能用

hash() :判斷是不是不可變數據類型

help() :得到源碼

callable() :判斷是不是可調用

int()

float():轉化為浮點數

complex():複數

bin() :轉化為二進制

oct():轉化為八進制

hex():轉化為十六進制

divmod(5,2):(2,1)商2餘1

round():五舍六入,奇變偶不變,默認是整數,可以指定保留幾位

pow(2,3):冪

bytes(s,encoding=’utf-8’):轉化為字節

ord():當前編碼 求ascii碼位

chr():用碼位求內容

repr():原型畢露

all():判斷元素是否都為真

any():判斷元素是否有真

globals():查看全局空間中的變量

locals():查看當前空間中的變量,有就打印字典,沒有就打印空字典

# s = """
# for i in range(10):
#     print(i)
# """
------------------------------------------------------
# s1 = """
# def func():
#     print(123)
# func()
# """
# print(eval(s))
# print(exec(s1))  # 牛逼 不能用
------------------------------------------------------
# print(hash("asdfas"))
------------------------------------------------------
# print(help(list))
# help(dict)
------------------------------------------------------
# def func():
#     pass
# print(callable(func))  # 查看是否可調用
------------------------------------------------------
# print(float(2))     # 浮點數
# print(complex(56))  # 複數
------------------------------------------------------
# print(oct(15))        # 八進制
# print(hex(15))        # 十六進制
------------------------------------------------------
# print(divmod(5,2))     # (2, 1) 2商 1餘
------------------------------------------------------
# print(round(5.3234,2))     # 四舍五入 -- 默認是整數,可以指定保留小數位
------------------------------------------------------
# print(pow(2,3))            # 冪
# print(pow(2,3,4))          # 冪,余
------------------------------------------------------
# s = "alex"
# print(bytes(s,encoding="utf-8"))
------------------------------------------------------
# print(ord("你"))    # 當前編碼
# print(chr(20320))
------------------------------------------------------
# s = "C:\u3000"
# print(repr(s))
------------------------------------------------------
# print("\u3000你好")
------------------------------------------------------
# lst = [1,2,3,False,4,5,6,7]
# print(all(lst))   # 判斷元素是否都為真  相似and
# print(any(lst))     # 判斷元素是否有真    相似or
------------------------------------------------------
# name = 1
# def func():
#     a = 123
#     # print(locals())
#     # print(globals())
# func()
------------------------------------------------------
# print(globals())   # 全局空間中的變量
# print(locals())   # 查看當前空間的變量
点赞

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *