标签:turn generator set python count dex dict ict ``
现在有个需求,列表[1, 2, 3, 4, 5, 6, 7, 8, 9],将列表里的每个值加1。
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = []
for item in a:
b.append(item + 1)
a = b
print(a)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for index, ele in enumerate(a, 0):
a[index] += 1
print(a)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = list(map(lambda x:x+1,a))
print(a)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print([i + 1 for i in a])
print('\n'.join([''.join(['%d * %d = %-3d' % (i, j, i * j) for j in range(1, i + 1)]) for i in range(1, 10)]))
g = (i for i in range(5))
print(type(g),g.next())
# 使用next()取值
g = (i for i in range(5))
print(type(g))
print('开始取值')
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
# print(next(g)) # 报错:StopIteration,因为取不到值了
# 基本上不会使用next(),正确应该使用for循环。而且还不需要担心会报错。拿不到函数return返回值
g = (i for i in range(10))
for i in g:
print(i)
# 斐波拉契:1 1 2 3 5 8 13 21
def fbi(num):
n, a, b = 0, 0, 1
while n < num:
yield b # # 到这停止,可以理解为冻结当前代码。并且,把值返回给外面的next()
print(a, b)
a, b = b, a + b
n += 1
for i in fbi(2):
print(i)
# 生成器send,相当于唤醒。
def work(n):
count = 0
while count < n:
count += 1
sign = yield count
print('sign的值:',sign)
if not sign:
yield count + 2
new_range = work(4)
# res = next(new_range) # 开始第一次取值 拿到一个1
# print(res) # 1
# res1 = new_range.send(True) # 第二次取值 发送一个true 函数遇到true 循环
# print(res1) # 2
# res2 = new_range.send(False) # 第三次取值 n=3
# print(res2)
这些类型称为可迭代对象:iterable
```python
from collections import Iterable
print(isinstance([],Iterable))
print(isinstance(‘‘,Iterable))
print(isinstance({},Iterable))
print(isinstance(set(),Iterable))
print(isinstance((i for i in range(2)),Iterable))
```
from collections import Iterator
print(isinstance((i for i in range(2)),Iterator))
标签:turn generator set python count dex dict ict ``
原文地址:https://www.cnblogs.com/xjmlove/p/10337607.html