Python-递推构造列表和字典

Python-递推式构造链表(List comprehension)

格式

alist = [expresion for item in list (if condition)]

其中if condition可以省略

示例

even = [x for x in range(0, 11) if x%2==0] #10以内的偶数
six = [(x,y) for x in range(20) for y in range(20) if x*y%6==0 and x#可以这样嵌套

递推构造字典

格式和递推构造链表相似

s = "world"
dic = {c:c.upper() for c in s}

你可能感兴趣的:(Python)