基础版:

variable = [out_exp for item in list if (expression == true)]

如:

li = [i*i for i in range(10) if i % 2]

输出:

  • [1, 9, 25, 49, 81]

if也可以省略

li = [i for i in range(10)]

输入:

  • [0,1,2,3,4,5,6,7,8,9]

for/if均可以多层嵌套

li = [i+j+k for i in "123"  for j in "abc"  for k in "ABC"]

输出结果:

  • [‘1aA’, ‘1aB’, ‘1aC’, ‘1bA’, ‘1bB’, ‘1bC’, ‘1cA’, ‘1cB’, ‘1cC’, ‘2aA’, ‘2aB’, ‘2aC’, ‘2bA’, ‘2bB’, ‘2bC’, ‘2cA’, ‘2cB’, ‘2cC’, ‘3aA’, ‘3aB’, ‘3aC’, ‘3bA’, ‘3bB’, ‘3bC’, ‘3cA’, ‘3cB’, ‘3cC’]
li = [i+j+k for i in "123" if i != '1' for j in "abc" if j != 'a' for k in "ABC"]

输出结果:

  • [‘2bA’, ‘2bB’, ‘2bC’, ‘2cA’, ‘2cB’, ‘2cC’, ‘3bA’, ‘3bB’, ‘3bC’, ‘3cA’, ‘3cB’, ‘3cC’]