# Python 列表推导式：简洁、高效的数据操作艺术

Python 的列表推导式，这个看似简单的语法糖，实则内含无限威力。在 Python 代码编写中，列表推导式的灵活性和简洁性让它成为了不可或缺的一部分。在这篇文章中，我们将更全面、更深入地探讨列表推导式，从基础的概念认识，到各类进阶的用法和操作，我们一一揭秘。最后，我们还将在 "One More Thing" 部分分享一个非常有趣且实用的列表推导式技巧，这会让你在编程道路上又多一份强大的工具。

## 1. 列表推导式：语法糖的力量

[expression for item in iterable]


squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


## 2. 过滤元素：带条件的列表推导式

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]


## 3. 复杂的数据结构：嵌套的列表推导式

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [x for sublist in nested_list for x in sublist]
print(flattened_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]


## 4. 数据变形：带表达式的列表推导式

strings = ['Hello', 'World', 'In', 'Python']
lowercase_strings = [s.lower() for s in strings]
print(lowercase_strings) # Output: ['hello', 'world', 'in', 'python']


## 5. 推广至其他数据结构：字典和集合的推导式

squared_dict = {x: x**2 for x in range(5)}
print(squared_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

squared_set = {x**2 for x in range(5)}
print(squared_set) # Output: {0, 1, 4, 16, 9}


## 6. 性能优化：列表推导式与 map/filter 的比较

import time

# Using list comprehension
start_time = time.time()
squares = [x**2 for x in range(1000000)]
end_time = time.time()
print(f"List comprehension took {end_time - start_time} seconds")

# Using map function
start_time = time.time()
squares = list(map(lambda x: x**2, range(1000000)))
end_time = time.time()
print(f"Map function took {end_time - start_time} seconds")


# One More Thing

perms = [(x, y, z) for x in range(3) for y in range(3) for z in range(3) if x != y and y != z and x != z]
print(perms) # Output: [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]