列表推导

  1. [x for x in range(1, 10)]

字典推导

  1. {x : x % 2 == 0 for x in range(1, 10)}

集合推导

  1. (x for x in range(1, 10))
  1. #列表推导
  2. list_info = [num for num in some_list if num & 2 == 0]
  3. #集合推导
  4. set_info = (num for num in some_list if num % 2 == 0)
  5. #字典推导
  6. --------------
  7. {8, 2, 4, 6}
  8. dict_info = {num : num % 2 == 0 for num in range(1, 11)}
  9. -------------------------------------------
  10. #{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}
  11. #应用
  12. print({x: y for x, y in enumerate(some_list)})
  13. ---------------------
  14. #{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9}
  15. #列表推导式+三元运算符
  16. info = [x**2 if (x > 5) else x**4 for x in range(1, 10)]
  17. print(info)
  18. ---------------------------
  19. #[1, 16, 81, 256, 625, 36, 49, 64, 81]