编程语言
首页 > 编程语言> > python-列表-for

python-列表-for

作者:互联网

普通for循环列表
1 lb2 = [1,2,3,4,5,6,7,8,9,10]
2 oddlist = []
3 #普通 for 循环
4 for i in lb2:
5     #1次循环oddlist[0:0] =[i],这里i是要赋值给列表,要加中括号,i是列表中的值
6     # 2次循环oddlist[1:1] =[i],因为第一次循环后len(oddlist)的长度是1
7     oddlist[len(oddlist):] = [i]
8 print(oddlist)
9 #结果:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

 
单循环推导式带判断


1 lb2 = [1,2,3,4,5,6,7,8,9,10]
2 #单循环推导式带判断
3 var = [ i for i in lb2 if i % 2 == 1 ]
4 print(var)
5 #结果:[1, 3, 5, 7, 9]

 



双循环推导式
1 colors1 = ['红','粉','黄']
2 colors2 = ['青','蓝','紫']
3 #双循环推导式
4 result = [ i + j for i in colors1 for j in colors2]
5 print(result)
6 # 结果:['红青', '红蓝', '红紫', '粉青', '粉蓝', '粉紫', '黄青', '黄蓝', '黄紫']

 



双循环推导式带判断条件
1 colors1 = ['红','粉','黄']
2 colors2 = ['青','蓝','紫']
3 #双循环推导式带判断条件
4 result = [ i + j for i in colors1 for j in colors2 if i == '红']
5 print(result)
6 # 结果:['红青', '红蓝', '红紫']

 

 

标签:oddlist,推导,双循环,python,colors2,colors1,列表,result
来源: https://www.cnblogs.com/lws865/p/10831083.html