""" 1、 生成[0,1,2,3,4,5,6]这样列表 """print(list(range(0,7)))""" 2、 生成[0,1,4,9,16,25]的列表, 即:0*0,1*1,2*2.....5*5 """# 1) 基本方法-繁琐方法
list1 =list()for one inrange(0,6):
list1.append(one * one)# 2) 列表表达式-简化方式
list1 =[one * one for one inrange(0,6)]print(list1)"""3、【if判断】获取1到20之间的属于偶数的正整数"""
list2 =[x for x inrange(1,21)if x %2==0]print(list2)"""4、【双for循环】遍历两列表,并逐一组合条件"""
M, N =["A1","B1","C1"],["M","N","C1"]
list3 =[f"{m}+{n}"for m in M for n in N if m != n]
list4 =[f"{m}+{n}"if m != n else m for m in M for n in N]# 如果有else条件, if 和else逻辑均在for前print(list3)print(list4)"""5、【遍历dict】提取用户信息,并列表存储,元素= 属性=属性值"""
student1 ={"name":"Lujier","sex":"Female","height":1.65,"hair":"long"}
stu_info_list =[f"{stu_key}={stu_value}"for stu_key, stu_value in student1.items()]print(stu_info_list)
# 1、 基本内容
L =[x * x for x inrange(5)]# print(L)
g =(x * x for x inrange(5))print(g)# 通过next()函数获得generator的下一个返回值print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))# 无元素可访问,会报错StopIterationprint(next(g))for one in g:print(one)
#2、 经典案例-斐波拉契# [普通实现]斐波拉契数列用列表生成式-前n个数deffibonacci_sequence(num):
n, current_before, current =1,0,1while n < num +1:print(current)
n, current_before, current = n +1, current, current_before + current
# [生成器]斐波拉契数列deffib(num):
n, current_before, current =1,0,1while n < num +1:yield current
n, current_before, current = n +1, current, current_before + current
fibonacci_sequence(7)print(fib(7))
mm = fib(7)print(next(mm))print(next(mm))
# 3、经典案例3-杨辉三角deftriangles(top_num):
n, before, current =2,[1],[1,1]while n < top_num +1:yield before
n, before = n +1, current
current =[1]+[current[index]+ current[index +