推导式
- 用一句话来生成一个列表
- 语法:[结果 for循环 条件判断]
- 列表推导式:[结果 for循环 条件筛选](鸡)
- 字典推导式:{k:v for循环 条件筛选}
- 集合推导式:{k for循环 条件}
列表推导式
lst = ['python'+str(i) for i in range(6) if i%2==1]
print(lst)
----------------------------------------------
['python1', 'python3', 'python5']
===============================
#找到名字里有两个e的名字 names = [['Tom','Billy','Jefferson','Andrew'],['Alice','Jill','Jennifer']] lst = [name for line in names for name in line if name.count('e')==2] print(lst) ---------------------- ['Jefferson', 'Jennifer'] ====================================
字典推导式
将[11,22,33,44]转换成{0:11,1:22,2:,3:44}
lst = [11,22,33,44]
dic = {i:lst[i] for i in range(len(lst)) if i < 2}
print(dic)
---------------------------
{0: 11, 1: 22}
====================
键值对换
dic = {'jj':'林俊杰','jay':'周杰伦'}
new_dic = {v:k for k,v in dic.items()}
print(new_dic)
-----------------------------------
{'林俊杰': 'jj', '周杰伦': 'jay'}
======================
集合推导式
去重操作
lst = [1,1,2,2,5,4,2,5,7,9]
s = {i for i in lst}
print(s)
----------------------------------------
{1, 2, 4, 5, 7, 9}
===============================