搜尋此網誌

2026年5月19日星期二

List comprehensions

List comprehensions in Python are a concise way to build new lists by looping through an iterable, applying an expression, and optionally filtering with conditions—all in a single line. They are faster and more readable than traditional for loops for simple transformations.

nums = [1, 2, 3, 4]

squares = [n**2 for n in nums]

print(squares)   # [1, 4, 9, 16]


nums = [1, 2, 3, 4, 5, 6]

evens = [n for n in nums if n % 2 == 0]

print(evens)   # [2, 4, 6]

>>> myList = list(range(100))
... filteredList = [item for item in myList if item % 10 == 0]
... print(filteredList)
...
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

>>> hisString = 'His name is Samson. He lives in Tuen Mun'
>>> hisString.split('.')
['His name is Samson', ' He lives in Tuen Mun']

>>> hisString.split()
['His', 'name', 'is', 'Samson.', 'He', 'lives', 'in', 'Tuen', 'Mun']

>>> def cleanWord(word):
...         return word.replace('.', '').lower()
...    [cleanWord(word) for word in hisString.split()]
...
['his', 'name', 'is', 'samson', 'he', 'lives', 'in', 'tuen', 'mun']

Outer square brackets [...]

Define that the result will be a list.

Without them, you’d have a generator expression instead (which doesn’t immediately build a list).

.lower()
Converts the string to lowercase.
Ensures consistency (e.g., "Samson" → "samson").

>>> [cleanWord(word) for word in hisString.split() if len(cleanWord(word)) < 3]

['is', 'he', 'in']

word → is a string (e.g., "he", "is", "mun").

You cannot directly compare a string to a number (word < 3) because Python doesn’t know how to order a string against an integer.

Doing so would raise a TypeError.

len(cleanWord(word)) → is an integer (the number of characters in the cleaned word).

This can be compared to another integer (< 3) safely.

Example: "he" → len("he") = 2 → 2 < 3 ✅


Nested list comprehension

>>> [[cleanWord(word) for word in sentence.split()] for sentence in hisString.split('.')]
[['his', 'name', 'is', 'samson'], ['he', 'lives', 'in', 'tuen', 'mun']]

Outer comprehension:
[ ... for sentence in hisString.split('.')]
Splits hisString into sentences using "." as the delimiter (定界符).
Iterates over each sentence.
For each sentence, it produces a list of cleaned words.

Inner comprehension:
[cleanWord(word) for word in sentence.split()]
Splits the current sentence into words (default split on whitespace).
Applies cleanWord(word) to each word.
Produces a list of cleaned words for that sentence.

Inner brackets → build a list of cleaned words per sentence.
Outer brackets → collect those lists into one big list.
Together → you get a nested list comprehension that structures text into sentences → words → cleaned words.

The variable sentence is a string (str).

Microsoft Copilot

沒有留言:

發佈留言