python 生成式

1. 列表生成式

//
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

redata = []
for i in arr:
    if i % 2 != 0:
        redata.append(i)

print(redata)
//
result = [ i  for i in arr if i % 2 != 0 ]
print(result)

[1, 3, 5, 7, 9]

2. 字典生成式

// 
d = {'a': 1, 'b': 2}

optd = {}
for k, v in d.items():
    optd[v] = k
print(optd)
//
optd = {v: k for k, v in d.items()}
print(optd)

{1: 'a', 2: 'b'}

3. 集合生成式

arr = [1, 2, 3]

result = { x ** 2 for x in arr}
print(result)

{1, 4, 9}