Python课程第九天_下午_课程笔记(列表生成式和生成器)

Day_09_PM_List_Generators

# 生成列表
l = [1, 2, 3, 4, 5]

l = list(range(1, 6))

l = []
for i in range(1, 6):
    l.append(i)

# 列表生成式/列表推导式: 掌握(存有限的比较少的数,占的内存较少)
l = [i for i in range(1, 6)]  # [1, 2, 3, 4, 5]
l = [i * i for i in range(1, 6)]  # [1, 4, 9, 16, 25]
l = [i for i in range(1, 6) if i % 2]  # [1, 3, 5], 1就是True,0是False不取
l = [i for i in range(1, 6) if i % 2 and i > 2]  # [3, 5]
l = [i for i in range(1, 6) if i % 2 and i < 5]  # [1, 3]
l = [i + j for i in '123' for j in 'abc']
#  => ['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']

print(l)

l1 = [1, 2, 3, 4, 5]
l2 = [i * 10 for i in l1]  # [10, 20, 30, 40, 50]
print(l2)

# 字典生成式: 了解
d = {i: i * i for i in range(5)}  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
print(d)

# 集合生成式: 了解
s = {i * i for i in range(5)}  # {0, 1, 4, 9, 16}
print(s)

# 生成器: generator(可以用于需要很多内存的,一次调一个)
# 一般用于: 超多的数或无穷多个的数
g = (i for i in range(1, 6))  # <generator object <genexpr> at 0x00000000021580C0> (内存地址)
# print(g)  # 生成器对象(只能一个一个去用)


# 需要使用next()来调用生成器
# print(next(g))  # 1
# print(next(g))  # 2
# print(next(g))  # 3
# print(next(g))  # 4
# print(next(g))  # 5
# print(next(g))  # 报错了, StopIteration

# 使用for-in来调用生成器, 不会报错
for i in g:
    print('i =', i)
print()


# 生成器函数: 有yield关键字的函数
# yield:
#   1.写在函数中, 会让函数变成生成器函数
#   2.每次使用next调用,会在yield暂停
#   3,类似return,可以返回值,但是不会结束函数
def fg():
    print('111')
    yield 100  # 暂停并返回, 会继续往下走,

    print('222')
    yield 200
    print('333')


g = fg()
# print(g)  # 生成器对象

print(next(g))  # 100
print(next(g))  # 200
print(next(g))  # 300  StopIteration
©️2020 CSDN 皮肤主题: 我行我“速” 设计师:Amelia_0503 返回首页