杰瑞科技汇

Python comprehension 如何高效使用?

Of course! Let's dive deep into Python comprehensions. They are a powerful and elegant feature that allows you to create sequences (like lists, dictionaries, and sets) in a very concise and readable way.

Python comprehension 如何高效使用?-图1
(图片来源网络,侵删)

We'll cover three main types:

  1. List Comprehensions (most common)
  2. Dictionary Comprehensions
  3. Set Comprehensions

We'll also briefly touch on a related concept: Generator Expressions.


List Comprehensions

A list comprehension provides a short syntax for creating a new list based on the values of an existing iterable (like a list, tuple, string, or range).

The Basic Syntax

The general structure is:

Python comprehension 如何高效使用?-图2
(图片来源网络,侵删)
new_list = [expression for item in iterable if condition]

Let's break it down:

  • expression: The operation or value you want to put into the new list. It can be the item itself, or a transformation of it (e.g., item * 2, item.upper()).
  • for item in iterable: This is a standard for loop. It iterates over each element in the given iterable.
  • if condition (optional): This is a filter. Only items that satisfy this condition will be processed and included in the new list.

Examples

Let's compare the "old" way (using a for loop) with the "new" way (using a comprehension).

Example 1: Simple Transformation

  • Goal: Create a list of squares for numbers from 0 to 9.
# The "Old" Way (using a for loop)
squares_old = []
for number in range(10):
    squares_old.append(number ** 2)
print(squares_old)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# The "New" Way (using a list comprehension)
squares_new = [number ** 2 for number in range(10)]
print(squares_new)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 2: Adding a Condition

Python comprehension 如何高效使用?-图3
(图片来源网络,侵删)
  • Goal: Get the squares of only the even numbers from 0 to 9.
# The "Old" Way
even_squares_old = []
for number in range(10):
    if number % 2 == 0:
        even_squares_old.append(number ** 2)
print(even_squares_old)
# Output: [0, 4, 16, 36, 64]
# The "New" Way
even_squares_new = [number ** 2 for number in range(10) if number % 2 == 0]
print(even_squares_new)
# Output: [0, 4, 16, 36, 64]

Example 3: Working with Strings

  • Goal: Get a list of the lengths of each word in a sentence, but only for words longer than 3 characters.
sentence = "Comprehensions are a powerful and elegant feature"
# The "Old" Way
word_lengths_old = []
for word in sentence.split():
    if len(word) > 3:
        word_lengths_old.append(len(word))
print(word_lengths_old)
# Output: [13, 4, 7, 9, 8]
# The "New" Way
word_lengths_new = [len(word) for word in sentence.split() if len(word) > 3]
print(word_lengths_new)
# Output: [13, 4, 7, 9, 8]

Dictionary Comprehensions

Dictionary comprehensions are very similar to list comprehensions, but they create dictionaries. They use curly braces and require a key: value pair.

The Basic Syntax

new_dict = {key_expression: value_expression for item in iterable if condition}

Examples

Example 1: Creating a mapping

  • Goal: Create a dictionary where numbers (keys) are mapped to their squares (values).
# The "Old" Way
square_map_old = {}
for number in range(5):
    square_map_old[number] = number ** 2
print(square_map_old)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# The "New" Way
square_map_new = {number: number ** 2 for number in range(5)}
print(square_map_new)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Example 2: Swapping keys and values

  • Goal: Swap the keys and values of an existing dictionary.
original_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {value: key for key, value in original_dict.items()}
print(swapped_dict)
# Output: {1: 'a', 2: 'b', 3: 'c'}

Set Comprehensions

Set comprehensions create sets (which are collections of unique items). They also use curly braces .

The Basic Syntax

new_set = {expression for item in iterable if condition}

Notice how this looks identical to a dictionary comprehension, but there's only one expression (no key: pair).

Examples

Example 1: Getting unique values

  • Goal: Get a set of all unique characters in a string, converted to uppercase.
text = "hello world"
# The "Old" Way
unique_chars_old = set()
for char in text:
    if char != ' ': # Filter out spaces
        unique_chars_old.add(char.upper())
print(unique_chars_old)
# Output: {'H', 'E', 'L', 'O', 'W', 'R', 'D'}
# The "New" Way
unique_chars_new = {char.upper() for char in text if char != ' '}
print(unique_chars_new)
# Output: {'H', 'E', 'L', 'O', 'W', 'R', 'D'}

Generator Expressions

Generator expressions look like list comprehensions but use parentheses instead of square brackets []. They don't build the entire list in memory at once. Instead, they create a generator object that produces items one at a time, which is much more memory-efficient for large datasets.

The Basic Syntax

generator_object = (expression for item in iterable if condition)

Example

  • Goal: Calculate the sum of squares for a very large range (e.g., 1 to 1,000,000).
# This would create a HUGE list in memory first, then sum it.
# Not recommended for large ranges.
# sum_of_squares_list = sum([x**2 for x in range(1, 1000000)])
# This is the memory-efficient way using a generator.
# The generator produces one square at a time for the sum() function.
sum_of_squares_gen = sum(x**2 for x in range(1, 1000000))
print(f"The sum is: {sum_of_squares_gen}")

You can often omit the extra parentheses if a generator expression is the only argument to a function.

# These are equivalent
gen1 = (x for x in range(10))
sum1 = sum(gen1)
sum2 = sum(x for x in range(10))

Summary Table

Type Syntax Example Output Use Case
List [expr for item in iterable] [1, 4, 9, 16] When you need an ordered, potentially duplicate list of items.
Dictionary {key: val for item in iterable} {'a': 1, 'b': 4, 'c': 9} When you need a key-value mapping.
Set {expr for item in iterable} {'a', 'b', 'c'} When you need a collection of unique items.
Generator (expr for item in iterable) A generator object (e.g., <generator object ...>) For memory-efficient iteration over large data.

When to Use Comprehensions (and When Not To)

Use comprehensions when:

  • The logic is simple and fits on one or two lines.
  • You are creating a new list, dict, or set from an existing iterable.
  • Readability is improved by the concise syntax.

Avoid comprehensions when:

  • The logic is complex, with multiple nested if/else statements or loops. A standard for loop will be more readable.
  • The logic inside the comprehension has significant side effects (like printing or modifying external variables).
  • You need to handle exceptions within the loop logic.

In short, comprehensions are a fantastic tool

分享:
扫描分享到社交APP
上一篇
下一篇