List Comprehensions
- List comprehensions 是 list 在 Python.
- list 它们允许您通过将表达式应用于现有迭代中的每个项目(例如, list 元组,字符串)并根据条件过滤项目 来生成新的。
- 推导式的语法 list 是:
[expression for item in iterable if condition]
例子:
# List comprehension to generate a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# List comprehension to filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Dictionary Comprehensions
- Dictionary comprehensions 允许您以简洁的方式创建字典。
- 与 类似,它们 通过将表达式应用于可迭代中的每个项目并根据条件过滤项目来 list comprehensions 生成新的。 dictionary
- 推导式的语法 dictionary 是:
{key_expression: value_expression for item in iterable if condition}
例子:
# Dictionary comprehension to create a dictionary of squares of numbers from 0 to 9
squares_dict = {x: x**2 for x in range(10)}
print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# Dictionary comprehension to filter even numbers from a dictionary
numbers_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
even_numbers_dict = {key: value for key, value in numbers_dict.items() if key % 2 == 0}
print(even_numbers_dict) # Output: {2: 'two', 4: 'four'}
Set Comprehensions
- Set comprehensions 允许您以与和 set 类似的方式 创建s 。 list comprehensions dictionary comprehensions
- set 它们通过将表达式应用于可迭代中的每个项目并根据条件过滤项目来 生成新项目。
- 推导式的语法 set 是:
{expression for item in iterable if condition}
例子:
# Set comprehension to create a set of squares of numbers from 0 to 9
squares_set = {x**2 for x in range(10)}
print(squares_set) # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
# Set comprehension to filter even numbers from a set
numbers_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even_numbers_set = {x for x in numbers_set if x % 2 == 0}
print(even_numbers_set) # Output: {2, 4, 6, 8, 10}
Comprehensions in Python 提供了一种简洁易读的方式来创建 list s、字典和 set 基于现有可迭代的 s,使您的代码更加优雅和高效。