生成式

1.判断是否迭代,reversed()内置函数的了解

# iterable: 可迭代的; 可以for循环
from collections import Iterable

# isinstance(1, int)
print(isinstance(1,Iterable))
print(isinstance({1,2,3},Iterable))
#reversed()函数是返回序列seq的反向访问的迭代子。参数可以是列表,元组,字符串,不改变原对象
print( [i for  i  in reversed([1,2,3,4])])

2.列表声称式

import random
li = []
for i in range(10):
    li.append(random.randint(1,10))


# 普通的列表生成式;
print([random.randint(1,10) for i in range(10)])
print([i*i for i in range(1,8)])

[4, 4, 1, 6, 1, 4, 2, 3, 10, 2]
[1, 4, 9, 16, 25, 36, 49]

# 升级版本
# 1. 找出1~10之间所有的偶数;
# print([i for i in range(1,11) if i%2==0])
#
[2, 4, 6, 8, 10]
# 2.for嵌套for循环;                              
# 'ABC', '123'                               
print([i+j for i in 'ABC' for j in '123'])  
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

3.字典生成式

# 1. : 将所有的key值变为大写;

d = dict(a=1,b=2)
# 1-1. 传统方法:
new_d = {}
for i in d:   # 'a' 'b'
    new_d[i.upper()] = d[i]
print("key转化为大写的字典:", new_d)

# 1-2. 升级
print({k.upper():v for k,v in d.items()})

key转化为大写的字典: {‘A’: 1, ‘B’: 2}
{‘A’: 1, ‘B’: 2}

# # 2:大小写key值合并, 统一以小写key值输出;
d = dict(a=2, b=1, c=2, B=9, A=5)
## 2-2. 字典生成式:
print({k.lower():d.get(k.lower(),0)+d.get(k.upper(),0) for k in d})

#2-1. 传统方法:
# {'a':2, 'b':1, 'c':2}
new_d = {}

for k, v in d.items():
    low_k = k.lower()
    if low_k not in new_d:
        new_d[low_k] = v
    else:
        new_d[low_k] += v

print(new_d)

{‘a’: 7, ‘b’: 10, ‘c’: 2}
{‘a’: 7, ‘b’: 10, ‘c’: 2}
3.集合生成式

print({i ** 2 for i in {1, 2, 3}})
print({i ** 2 for i in {1, 2, 3, 9, 12} if i % 3 == 0})

{1, 4, 9}
{81, 9, 144}

猜你喜欢

转载自blog.csdn.net/qq_41661056/article/details/80358726