1、列表推导式
# 基本格式
variable = [expr for value in collection if condition]
变量 表达式 收集器 条件
例1:斐波那契序列
a = [i for i in range(10) if not (i %2) and (i % 3)]
# 相当于
for i in range(10):
if i % 2 ==0 and i %3 != 0:
print(i)
例2:过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
[name.upper() for name in names if len(name)>3]
['ALICE', 'JERRY', 'WENDY', 'SMITH']
相当于
names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
for name in names:
if len(name) > 3:
print(name.upper())
2 、字典推导式
# 基本格式
{ key_expr: value_expr for value in collection if condition }
例子
strings = ['import','is','with','if','file','exception']
>>> D = {key: val for val,key in enumerate(strings)}
>>> D
{'exception': 5, 'is': 1, 'file': 4, 'import': 0, 'with': 2, 'if': 3}
3、集合推导式
与列表推导式差不多,唯一的区别在于,集合是{}
例子
>>> strings = ['a','is','with','if','file','exception']
>>> {len(s) for s in strings} 中括号
{1, 2, 4, 9}
4、嵌套列表推导式
例子:一个由男人列表和女人列表组成的嵌套列表,取出姓名中带有两个以上字母e的姓名,组成列表
names = [['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'],
['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]
for 循环实现:
tmp = []
for lst in names:
for name in lst:
if name.count('e') >= 2:
tmp.append(name)
print(tmp)
#输出结果
>>>
['Jefferson', 'Wesley', 'Steven', 'Jennifer']
嵌套循环实现:
names = [['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'],
['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]
[name for lst in names for name in lst if name.count('e') >=2] #注意遍历顺序,这是实现的关键
#输出结果
>>>
['Jefferson', 'Wesley', 'Steven', 'Jennifer']