集合生成式相關示例
python
1、例如生成集合{1,4,9,16,25}ide
# for in 循環實現 S = set() for i in range(1,7): S.add(i * i) print(S) # {1, 4, 36, 9, 16, 25} # 集合生成式 S = { i * i for i in range(1,7)} print(S) # {1, 4, 36, 9, 16, 25}
2、 嵌套ifspa
# for in 循環嵌套if S = set() for i in range(1,7): if i % 2: S.add(i * i) print(S) # 集合生成式 S = { i * i for i in range(1,7) if i % 2} print(S)
3、循環嵌套it
# for in 循環 S = set() for i in range(1,4): for j in range(1,4): S.add((i,j)) print(S) # 集合生成式 S = { (i,j) for i in range(1,4) for j in range(1,4)} print(S)