递推式列表表达式
new_list = [expression(i) for i in old_list if filter(i)]
举例:要创建一个列表,是从零到十的平方,普通写法如下
squares = []
for x in range(11):
squares.append(x**2)
递推式列表写法如下
squares = [x**2 for x in range(11)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
另外递推式列表支持嵌套写法,如找出30以内所有能构成直角三角形的数组:
ret = [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2==z**2]
print(ret)
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]
递推式字典和递推式列表类似,只是[]替换成了{}
import string
print(string.ascii_lowercase)
# 递推式字典
dct = {c:ord(c) for c in string.ascii_lowercase}
print(dct)
# 递推式列表
lst = [ord(c) for c in string.ascii_lowercase]
print(lst)
dct即为生成的字典,dict字典是无序的,lst为生成的列表,是有序的,为26个英文字母的ascii码值集合。
ord函数返回参数字符的ASCII数值