1.列表推导式
#基本形式
[expr for val in collection if condition]
#等价于
result[]
for val in collection:
if condition:
result.append(expr)
In[1]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In[2]: [x.upper() for x in strings if len(x) > 2] #upper()方法将字母改为大写
Out[1]: ['BAT', 'CAR', 'DOVE', 'PYTHON']
2.集合推导式
#基本形式
set_comp = {expr for value in collection if condition}
In[1]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In[2]: length = {len(x) for x in strings}
In[3]: length
Out[1]: {1, 2, 3, 4, 6}
In[4]: set(map(len, strings)) #使用map函数也可以获得以上目标
Out[2]: {1, 2, 3, 4, 6}
3.字典推导式
#基本形式
dict_comp = {key_expr : value_expr for value in collection if condition}
In[1]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In[2]: mapping = {val : index for index, val in enumerate(strings)}
In[3]: mapping
Out[1]: {'a': 0, 'as': 1, 'bat':2, 'car': 3, 'dove': 4, 'python': 5}
4.嵌套推导式
#嵌套表达式的排列顺序以for循环的顺序为依据
list = []
for names in data:
enough = [name for name in names if name.count('e') >= 2]
list.extend(enough)
#等价于
result = [name for names in data for name in names if name.count('e') >= 2]
#列表推导式区分开有利于可读性
for tup in tuples:
for x in tup:
result.append(x)
[[x for x in tup] for tup in tuples]