Python 简明教程

Python - List Comprehension

List Comprehension in Python

list comprehension 是一种创建列表的简洁方法。它类似于数学中的集合生成器符号。它用于基于现有的可迭代对象(例如列表、元组或字符串)定义 list ,并对可迭代对象中的每个元素应用一个表达式。

A list comprehension is a concise way to create lists. It is similar to set builder notation in mathematics. It is used to define a list based on an existing iterable object, such as a list, tuple, or string, and apply an expression to each element in the iterable.

Syntax of Python List Comprehension

列表解析的基本语法如下:

The basic syntax of list comprehension is −

new_list = [expression for item in iterable if condition]

其中,

Where,

  1. expression is the operation or transformation to apply to each item in the iterable.

  2. item is the variable representing each element in the iterable.

  3. iterable is the sequence of elements to iterate over.

  4. condition (optional) is an expression that filters elements based on a specified condition.

Example of Python List Comprehension

假设我们要将字符串 “hello world” 中的所有字母转换为大写形式。使用列表解析,我们将遍历每个字符,检查它是否为字母,如果是,则将其转换为大写,从而生成一个大写字母列表:

Suppose we want to convert all the letters in the string "hello world" to their upper-case form. Using list comprehension, we iterate through each character, check if it is a letter, and if so, convert it to uppercase, resulting in a list of uppercase letters −

string = "hello world"
uppercase_letters = [char.upper() for char in string if char.isalpha()]
print(uppercase_letters)

获得的结果显示如下:

The result obtained is displayed as follows −

['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

List Comprehensions and Lambda

在 Python 中, lambda 是用于创建匿名函数的关键字。匿名函数是没有名字的定义的函数。这些函数使用 lambda 关键字创建,后面跟着逗号分隔的参数列表,然后是 : ,接着是要计算的表达式。

In Python, lambda is a keyword used to create anonymous functions. An anonymous function is a function defined without a name. These functions are created using the lambda keyword followed by a comma-separated list of arguments, followed by a colon :, and then the expression to be evaluated.

我们可以在解析中通过对解析中可迭代对象的每个元素应用 lambda 函数来使用具有 lambda 的列表解析,从而生成一个新列表。

We can use list comprehension with lambda by applying the lambda function to each element of an iterable within the comprehension, generating a new list.

Example

在以下示例中,我们使用带有 lambda 函数的列表解析来将给定列表 “original_list” 中的每个元素加倍。我们遍历 “original_list” 中的每个元素,并应用 lambda 函数进行加倍:

In the following example, we are using list comprehension with a lambda function to double each element in a given list "original_list". We iterate over each element in the "original_list" and apply the lambda function to double it −

original_list = [1, 2, 3, 4, 5]
doubled_list = [(lambda x: x * 2)(x) for x in original_list]
print(doubled_list)

以下是上面代码的输出: -

Following is the output of the above code −

[2, 4, 6, 8, 10]

Nested Loops in Python List Comprehension

Python 中的嵌套循环是另一个循环中的循环,其中对于外层循环的每次迭代,内层循环都会执行多次。

A nested loop in Python is a loop inside another loop, where the inner loop is executed multiple times for each iteration of the outer loop.

我们可以在列表解析中通过将一个循环放在另一个循环中来使用嵌套循环,从而简洁地从多次迭代中创建列表。

We can use nested loops in list comprehension by placing one loop inside another, allowing for concise creation of lists from multiple iterations.

Example

在此示例中,来自两个列表中的所有项目组合以元组形式添加到第三个列表对象中:

In this example, all combinations of items from two lists in the form of a tuple are added in a third list object −

list1=[1,2,3]
list2=[4,5,6]
CombLst=[(x,y) for x in list1 for y in list2]
print (CombLst)

它将生成如下输出:

It will produce the following output −

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Conditionals in Python List Comprehension

Python 中的条件是指使用 “if”、“elif”和 “else” 等语句来根据某些条件控制代码流。它们允许你根据条件是计算为 “True” 还是 “False” 来执行不同的代码块。

Conditionals in Python refer to the use of statements like "if", "elif", and "else" to control the flow of a code based on certain conditions. They allow you to execute different blocks of code depending on whether a condition evaluates to "True" or "False".

我们可以在列表解析中通过在可迭代对象之后和循环之前包含它们来使用条件,这将在生成列表时根据指定条件从可迭代对象中筛选元素。

We can use conditionals in list comprehension by including them after the iterable and before the loop, which filters elements from the iterable based on the specified condition while generating the list.

Example

以下示例在列表解析中使用条件来生成一个从 1 到 20 的偶数列表:

The following example uses conditionals within a list comprehension to generate a list of even numbers from 1 to 20 −

list1=[x for x in range(1,21) if x%2==0]
print (list1)

我们得到了如下输出 −

We get the output as follows −

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

List Comprehensions vs For Loop

列表解析和 for 循环都用于迭代,但它们在语法和用法上有所不同。

List comprehensions and for loops are both used for iteration, but they differ in terms of syntax and usage.

列表解析类似于 Python 中创建列表的快捷方式。它们允许你通过对现有列表中的每个元素应用操作来生成一个新列表。

List comprehensions are like shortcuts for creating lists in Python. They let you generate a new list by applying an operation to each item in an existing list.

另一方面,for 循环是一种控制流语句,用来逐步迭代可迭代元素,为每个元素执行代码块。

For loop, on the other hand, is a control flow statement used to iterate over elements of an iterable one by one, executing a block of code for each element.

Example Using For Loop

假设我们要分离字符串中的每个字母,并将所有非元音字母放入列表对象中。我们可以通过如下所示的 for 循环来做到这一点:

Suppose we want to separate each letter in a string and put all non-vowel letters in a list object. We can do it by a for loop as shown below −

chars=[]
for ch in 'TutorialsPoint':
   if ch not in 'aeiou':
      chars.append(ch)
print (chars)

chars 列表对象显示如下:

The chars list object is displayed as follows −

['T', 't', 'r', 'l', 's', 'P', 'n', 't']

Example Using List Comprehension

我们可以通过列表解析技术轻松获得相同的结果。列表解析的常规用法如下:

We can easily get the same result by a list comprehension technique. A general usage of list comprehension is as follows −

listObj = [x for x in iterable]

应用此规则,chars 列表可通过以下语句构造:

Applying this, chars list can be constructed by the following statement −

chars = [ char for char in 'TutorialsPoint' if char not in 'aeiou']
print (chars)

chars 列表将像以前一样显示:

The chars list will be displayed as before −

['T', 't', 'r', 'l', 's', 'P', 'n', 't']

Example

以下示例使用列表解析来构建 1 到 10 之间数字的平方列表:

The following example uses list comprehension to build a list of squares of numbers between 1 to 10 −

squares = [x*x for x in range(1,11)]
print (squares)

squares 列表对象为:

The squares list object is −

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Advantages of List Comprehension

以下是使用列表解析的优点:

Following are the advantages of using list comprehension −

  1. Conciseness − List comprehensions are more concise and readable compared to traditional for loops, allowing you to create lists with less code.

  2. Efficiency − List comprehensions are generally faster and more efficient than for loops because they are optimized internally by Python’s interpreter.

  3. Clarity − List comprehensions result in clearer and more expressive code, making it easier to understand the purpose and logic of the operation being performed.

  4. Reduced Chance of Errors − Since list comprehensions are more compact, there is less chance of errors compared to traditional for loops, reducing the likelihood of bugs in your code.