Python Comprehensions

List Comprehensions sind eine spezielle Syntax, mit der wir Listen aus anderen Listen erstellen können, und sie sind unglaublich nützlich beim Umgang mit Zahlen und mit ein oder zwei Ebenen verschachtelter for-Schleifen.

Aus dem Python 3 Tutorial

List comprehensions provide a concise way to create lists. [...] or to create a subsequence of those elements that satisfy a certain condition.

Lesen Sie Python Comprehensions: A step by step Introduction für eine eingehendere Einführung.

List comprehension

So erstellen wir eine neue Liste aus einer bestehenden Sammlung mit einer For-Schleife:

# Traditional approach: create list using a for loop
names = ['Charles', 'Susan', 'Patrick', 'George']

new_list = []
for n in names:
    new_list.append(n)

new_list
['Charles', 'Susan', 'Patrick', 'George']

Und so machen wir dasselbe mit einer List Comprehension:

# List comprehension: concise way to create a new list
# Syntax: [expression for item in iterable]
names = ['Charles', 'Susan', 'Patrick', 'George']

new_list = [n for n in names]  # Create list with all names
new_list
['Charles', 'Susan', 'Patrick', 'George']
Quiz

Melden Sie sich an, um dieses Quiz zu beantworten und Ihren Lernfortschritt zu verfolgen

What is the basic syntax of a list comprehension?
A. [expression for item in iterable]
B. (expression for item in iterable)
C. {expression for item in iterable}
D. expression for item in iterable

Dasselbe können wir mit Zahlen machen:

# Nested list comprehension: create tuples from two ranges
# Equivalent to nested for loops
n = [(a, b) for a in range(1, 3) for b in range(1, 3)]
n
[(1, 1), (1, 2), (2, 1), (2, 2)]

Hinzufügen von Bedingungen

Wenn wir möchten, dass new_list nur die Namen enthält, die mit C beginnen, würden wir dies mit einer For-Schleife wie folgt tun:

# Traditional approach: filter with if condition
names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']

new_list = []
for n in names:
    if n.startswith('C'):  # Filter names starting with 'C'
        new_list.append(n)

print(new_list)
['Charles', 'Carol']

In einer List Comprehension fügen wir die if-Anweisung am Ende hinzu:

# List comprehension with condition: filter items
# Syntax: [expression for item in iterable if condition]
new_list = [n for n in names if n.startswith('C')]
print(new_list)
['Charles', 'Carol']
Quiz

Melden Sie sich an, um dieses Quiz zu beantworten und Ihren Lernfortschritt zu verfolgen

Where does the if condition go in a list comprehension?
A. Before the for keyword
B. After the for clause
C. Inside the expression
D. Before the square brackets

Um eine if-else-Anweisung in einer List Comprehension zu verwenden:

# List comprehension with if-else: conditional expression
# Syntax: [expression_if_true if condition else expression_if_false for item in iterable]
nums = [1, 2, 3, 4, 5, 6]
new_list = [num*2 if num % 2 == 0 else num for num in nums]  # Double even numbers
print(new_list)
[1, 4, 3, 8, 5, 12]

Set and Dict comprehensions

The basics of `list` comprehensions also apply to sets and dictionaries.

Set comprehension

# Set comprehension: create a set using comprehension syntax
# Syntax: {expression for item in iterable}
b = {"abc", "def"}
{s.upper() for s in b}  # Convert all strings to uppercase
{"ABC", "DEF"}

Dict comprehension

# Dict comprehension: swap keys and values
# Syntax: {key_expression: value_expression for item in iterable}
c = {'name': 'Pooka', 'age': 5}
{v: k for k, v in c.items()}  # Reverse key-value pairs
{'Pooka': 'name', 5: 'age'}
Quiz

Melden Sie sich an, um dieses Quiz zu beantworten und Ihren Lernfortschritt zu verfolgen

What syntax is used for dictionary comprehensions?
A. [key: value for item in iterable]
B. (key: value for item in iterable)
C. {key_expression: value_expression for item in iterable}
D. {key, value for item in iterable}

Eine List Comprehension kann aus einem Dictionary generiert werden:

# List comprehension from dictionary: create formatted strings
c = {'name': 'Pooka', 'age': 5}
["{}:{}".format(k.upper(), v) for k, v in c.items()]  # Format as "KEY:value"
['NAME:Pooka', 'AGE:5']