# Python-列表推导式&生成器

### 文章目录

#### 列表推导式

##### 格式：

list1 = [生成元素的表达式 for 原列表的元素 in 原列表 if 需要满足的条件]

##### 使用：

list0 = [2, 5, 6, 7, 4]
list1 = [i * i for i in list0 if i % 2 == 0]
print(list1)
'''

[4, 36, 16]
'''

list0 = [2, 5, 6, 7, 4]
list1 = [i * i if i % 2 else -i for i in list0]
print(list1)
'''

[-2, 25, -6, 49, -4]
'''
# 这里Py的非零整数就是True，零就是False

list0 = ['abc', 'ccc', 'here', 'cute']
list1 = [i * 5 for i in list0 if len(i) > 3]
print(list1)
'''

['hereherehereherehere', 'cutecutecutecutecute']
'''

list0 = ['abc', 'ccc', 3, 'here', 'cute', 5, True, False]
list1 = [i for i in list0 if isinstance(i, str)]
print(list1)
'''

['abc', 'ccc', 'here', 'cute']
'''

list0 = [{'key': 10}, {'key': 34}, {'key': 66}]
list1 = [i for i in list0 if i['key'] <= 10]
print(list1)
'''

[{'key': 10}]
'''

list1 = [(i, j) for i in range(5) if i % 2 for j in range(5) if j % 2 == 0]
print(list1)
'''

[(1, 0), (1, 2), (1, 4), (3, 0), (3, 2), (3, 4)]
'''

##### 集合推导式

set1 = {i % 2 for i in range(10)}
print(set1)
''''

{0, 1}
''''
##### 字典推导式

dict0 = {'aaa': 233, 'bbb': 332, 'ddd': 555}
dict1 = {key: value + 5 for key, value in dict0.items()}
print(dict1)
'''

{'aaa': 238, 'bbb': 337, 'ddd': 560}
'''

dict0 = {'aaa': 233, 'bbb': 233, 'ddd': 555}
dict1 = {value: key for key, value in dict0.items()}
print(dict1)
'''

{233: 'bbb', 555: 'ddd'}
'''

#### 生成器

##### 生成器-表达式

list1 = (i * i for i in range(6))
print(list1)
'''

<generator object <genexpr> at 0x0000013E4C03F5C8>
'''

generator = (i * i for i in range(6))
print(generator.__next__()) # 使用自带的__next__()方法来返回下一个元素
print(generator.__next__())
'''

0
1
'''
generator = (i * i for i in range(6))
print(next(generator))# 使用系统自带的next函数
print(next(generator))
print(next(generator))
'''

0
1
4
'''

generator = (i * i for i in range(6))
for i in generator:
print(i)
'''

0
1
4
9
16
25
'''

generator = (i * i for i in range(6))
print(list(map(lambda x: x * x, generator)))
'''

[0, 1, 16, 81, 256, 625]
'''
##### 生成器-函数

###### yield关键字

def generator(n: int):
cnt = 1
while cnt < n:
cnt += n
yield cnt

print(generator(5))
'''

<generator object generator at 0x0000024845B154C8>
'''

1. ge获取到生成器对象的地址，但没有执行生成器内部的代码
2. 执行第一个next，开始执行内部的代码，先是执行最外层初始化cnt，然后进入循环，直到执行到yield关键字，把cnt当做当次获取的值返回了出去，然后生成器内部的执行停止
3. 执行第二个next，可以发现打印了‘yield后’说明第二次执行是接着上次yield结束的位置执行的
def generator(n: int):
cnt = 1
print("进入生成器")
while cnt < n:
cnt += 1
print("yield之前")
yield cnt
print("yield后")

ge = generator(5)
print("得到生成器----开始获取元素", end='\n\n\n')
print(ge.__next__())
print("第一个元素获取完毕", end='\n\n\n')
print(ge.__next__())
print("第二个元素获取完毕", end='\n\n\n')
'''

yield之前
2

yield后
yield之前
3

'''

def generator(n: int):
cnt = 1
print("进入生成器")
cnt += 1
yield cnt
yield 23333

ge = generator(5)
print(ge.__next__())
print(ge.__next__())
'''

2
23333
'''

###### 函数生成器与return

def generator(n: int):
cnt = 1
cnt += 1
yield cnt
yield 23333

ge = generator(5)
print(ge.__next__())
print(ge.__next__())
print(ge.__next__())
'''

2
23333
Traceback (most recent call last):
File "D:\Pycharm\Project\Pytest\test.py", line 11, in <module>
print(ge.__next__())
StopIteration
'''

def generator(n: int):
cnt = 1
cnt += 1
yield cnt
yield 23333
return "生成器结束"

ge = generator(5)
print(ge.__next__())
print(ge.__next__())
print(ge.__next__())
'''

Traceback (most recent call last):
2
File "D:\Pycharm\Project\Pytest\test.py", line 12, in <module>
23333
print(ge.__next__())
StopIteration: 生成器结束
'''
##### send方法

def generator(n: int):
cnt = 1
while cnt < n:
cnt += 1
message = yield cnt
print(message)

ge = generator(5)
print(ge.send(1005))
'''

Traceback (most recent call last):
File "D:\Pycharm\Project\Pytest\test.py", line 10, in <module>
print(ge.send(1005))
TypeError: can't send non-None value to a just-started generator
'''

def generator(n: int):
cnt = 1
while cnt < n:
cnt += 1
message = yield cnt
print(message)

ge = generator(5)
print(ge.send(None))
print(ge.send(1005))
print(ge.send(1005))
'''

2
1005
3
1005
4
'''

def generator(n: int):
cnt = 1
while cnt < n:
cnt += 1
message = yield cnt
print(message)

ge = generator(5)
print(ge.__next__())
print(ge.send(1005))
print(ge.send(1005))
'''

2
1005
3
1005
4
'''

10-27 41

05-04 283
09-15 890
08-17 28
09-05 617