列表推导式
看一下使用列表推导式与不使用列表推导式的差别
li = [] for i in range(0,5): li.append(i) li1 = [ i for i in range(0,5)] print(li) #[0, 1, 2, 3, 4] print(li1) #[0, 1, 2, 3, 4]
怎么样,一行代码就能搞定,是不是代码量减少了
li = [] for i in range(0,5): if i % 2 == 0: li.append(i) li1 = [ i for i in range(0,5) if i % 2 == 0] print(li) # [0, 2, 4] print(li1) # [0, 2, 4]
字典推导式
li = [‘电脑‘,‘手机‘,‘平板‘] dic = {key: value for value,key in enumerate(li)} print(dic) # {‘电脑‘: 0, ‘手机‘: 1, ‘平板‘: 2}
li = [1,2,3] li1 = [4,5,6] di = { li[i] : li1[i] for i in range(len(li))} print(di) # {1: 4, 2: 5, 3: 6}
dic = {‘张三‘:17,"李四":18,"王五":19} dic1 = { key:value for key,value in dic.items() if value >= 18} print(dic1) # {‘李四‘: 18, ‘王五‘: 19}
原文:https://www.cnblogs.com/learn-tester/p/15120101.html