""" 三目运算: 推导式 """ number = 100 if number > 60: print("及格") else: print("不及格") # 三目运算符 res = True if number > 60 else False print(res) # True # 需求,生成[py1,py2,....py10] li = [] for i in range(1, 11): # li.append("py{}".format(i)) li.append(f'py{i}') print(li) # ['py1', 'py2', 'py3', 'py4', 'py5', 'py6', 'py7', 'py8', 'py9', 'py10'] # 列表推导式 li = ['py{}'.format(i) for i in range(1, 11)] li2 = [f'py{i}' for i in range(1, 11)] print(li) print(li2) # ['py1', 'py2', 'py3', 'py4', 'py5', 'py6', 'py7', 'py8', 'py9', 'py10'] # 集合推导式 se = {f'py{i}' for i in range(1, 5)} print(se, type(se)) # {'py2', 'py3', 'py4', 'py1'} <class 'set'> # 字典推导式 # dic = {'name': i for i in range(1, 5)} # print(dic) # {'name': 4} # 字典中key唯一 dic = {'name{}'.format(i) for i in range(1, 5)} print(dic) # {'name2', 'name3', 'name4', 'name1'} dic = {'name{}'.format(i): i for i in range(1, 5)} print(dic) # {'name1': 1, 'name2': 2, 'name3': 3, 'name4': 4} dic = {'name{}'.format(i): i*10 for i in range(1, 5)} print(dic) # {'name1': 10, 'name2': 20, 'name3': 30, 'name4': 40} # 生成器表达式 cook_str = 'BIDUPSID=D0727533D7147B7;PSTM=1530348042;BAIDUID=B1005C9BC2EB28;sugstore=0;__cfduid=d0a13458f8ac2a;BD_UPN=12314353;ispeed_lsm=2;BDORZ=B490B5EBF6F3CD402' res = cook_str.split(';') print(res) # ['BIDUPSID=D0727533D7147B7', 'PSTM=1530348042', 'BAIDUID=B1005C9BC2EB28', 'sugstore=0', # '__cfduid=d0a13458f8ac2a', 'BD_UPN=12314353', 'ispeed_lsm=2', 'BDORZ=B490B5EBF6F3CD402' res1 = res[0].split("=") print(res1) # ['BIDUPSID', 'D0727533D7147B7'] dic = {i.split('=')[0]: i.split('=')[1] for i in res} print(dic) # {'BIDUPSID': 'D0727533D7147B7', 'PSTM': '1530348042', 'BAIDUID': 'B1005C9BC2EB28', 'sugstore': '0', # '__cfduid': 'd0a13458f8ac2a', 'BD_UPN': '12314353', 'ispeed_lsm': '2', 'BDORZ': 'B490B5EBF6F3CD402'}