names=['lilly','tom','jimmy','andy','da']
result=[name for name in names if len(name)>3]
print(result)
result1=[name.capitalize() for name in names if len(name)>3]
print(result1)
result2=[i for i in range(1,101) if i%3==0 and i%5==0]
print(result2)
result3=[(x,y) for x in range(5) if x%2==0 for y in range(7) if y%2!=0]
print(result3)
list=[[1,2,3],[4,5,6],[7,8,9]]
result4=[i[-1] for i in list]
print(result4)
dict1={'name':'tom','salary':5000}
dict2={'name':'andy','salary':4000}
dict3={'name':'silly','salary':5080}
dict4={'name':'lilly','salary':4820}
list2=[dict1,dict2,dict3,dict4]
result5=[employee['salary']+200 if employee['salary']>5000 else employee['salary']-200 for employee in list2]
print(result5)
dict5={'a':'A','b':'B','c':'C','d':'D'}
newdict={value:key for key,value in dict5.items()}
print(newdict)
list=[x*3 for x in range(20)]
print(list)
g=(x*3 for x in range(20))
print(g.__next__())
print(g.__next__())
print(next(g))
print(next(g))
while 1:
try:
print(next(g))
except StopIteration:
print('没有更多元素了')
break
def func():
n=0
while True:
n+=1
yield n
func()
'''
1、定义一个函数,函数中使用yield关键字
2、调用函数,接收调用结果
3、得到的结果g就是生成器
4、借助于next(g),g.__next__()
'''
def func():
n=0
while True:
n+=1
yield n
g=func()
print(g)
print(next(g))
print(g.__next__())
def fib(length):
a,b=0,1
n=0
while n<length:
yield b
t=b
b=a+b
a=t
n=n+1
return '没有更多元素了'
g=fib(8)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
'''
生成器:
1、__next__()#获取下一个元素
2、send(value)#向每次生成器调用中传值。注意:第一次调用send(None)
'''
def gen():
i=0
while i<5:
temp=yield i
print('temp:',temp)
i=i+1
return '没有更多元素了'
g=gen()
print(g.send(None))
n1=g.send('呵呵')
print('n1',n1)
n2=g.send('哈哈')
print('n2',n2)
def task1(n):
for i in range(n):
print('正在搬第{}块砖'.format(i))
yield
def task2(n):
for i in range(n):
print('正在听第{}首歌'.format(i))
yield
g1=task1(5)
g2=task2(5)
while True:
try:
next(g1)
next(g2)
except:
break
from collections.abc import Iterable
list1=[1,2,3,4]
f=isinstance(list1,Iterable)
print(f)
list1=iter(list1)