python笔记之好玩的列表:列表推导式

列表推导式(List comprehensions)也叫列表解析,灵感取自函数式编程语言Haskell,可以用来动态的创建列表,语法如下:

[有关A的表达式 for A in B]

例如:

1 >>> list1 = [x**2 for x in range(10)]
2 >>> list1
3 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

相当于:

1 list1 = []
2 for x in range(10):
3     list1.append(x**2)

测试1:先运行下获得结果再把列表推导式还原出来:

1 >>> list1 = [(x, y) for x in range(10) for y in range(10) if x%2==0 if y%2!=0]

答案:

1 list1 = []
2 for x in range(10):
3     for y in range(10):
4         if x%2 == 0 and y%2 !=0:
5             list1.append((x, y))
View Code

测试2:有代码如下

1 list1 = ['1.80','2.90','3.70','4.60']
2 list2 = ['4.D','2.A','3.C','1.B']
3 
4 #此处填写代码
5 
6 for each in list3:
7     print(each)

打印的结果如下

1.B:80
2.A:90
3.C:70
4.D:60

答案:

用列表推导式:

1 list3 = [result + '' + score[2:] for score in list1 for result in list2 if score[0] == result[0]]
View Code

正常方式:

1 list3 = []
2 for score in list1:
3     for result in list2:
4         if score[0] == result[0]:
5             list3.append(result + ":" + score[2:])
View Code
原文地址:https://www.cnblogs.com/lanhoo/p/7688288.html