📅  最后修改于: 2023-12-03 14:42:11.201000             🧑  作者: Mango
List comprehension is a concise and elegant way to create new lists in Python. It allows you to transform, filter, and manipulate elements from an existing list to create a new list in a single line of code.
The general syntax of list comprehension is:
new_list = [expression for item in iterable if condition]
Let's see some examples to get a better understanding of list comprehension.
numbers = [1, 2, 3, 4, 5]
doubled = [num * 2 for num in numbers]
# doubled: [2, 4, 6, 8, 10]
evens = [num for num in range(1, 11) if num % 2 == 0]
# evens: [2, 4, 6, 8, 10]
sentence = "Hello, world!"
consonants = [char for char in sentence if char.lower() not in 'aeiou']
# consonants: ['H', 'l', 'l', ',', ' ', 'w', 'r', 'l', 'd', '!']
squares = [num ** 2 for num in range(10) if num % 3 == 0]
# squares: [0, 9, 36, 81]
List comprehension can be a powerful tool to simplify your code and make it more readable. It is a commonly used technique in Python programming, and mastering it can greatly enhance your productivity as a programmer.
For more information, refer to the Python documentation on list comprehension.