列表生成式的 for 循环后面还能够加上 if 判断。例如:python
[x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
若是咱们只想要偶数的平方,不改动 range()的状况下,能够加上 if 来筛选:code
[x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]
有了 if 条件,只有 if 判断为 True 的时候,才把循环的当前元素添加到列表中。字符串
def toUppers(L): return [x.upper() for x in L if isinstance(x, str)] print toUppers(['Hello', 'world', 101])
isinstance(x, str) 能够判断变量 x 是不是字符串;class