Python 推导式

2024 年 8 月 29 日 | 4 分钟阅读

在本文中,我们将探讨 Python 中列表、字典、集合和生成器等数据结构中的推导式用法。

推导式提供了一种简洁的 Python 编程方式。它在不影响代码可读性的情况下,减小了代码的体积。

因此,本文将讨论以下几种推导式:

  1. 列表推导式
  2. 字典推导式
  3. 集合推导式
  4. 生成器推导式

列表推导式

我们知道列表的元素用方括号括起来,并且可以包含不同数据类型的数值。

在下面的程序中,我们将从列表中提取出偶数。

让我们来看下面的列表示例。

示例 -

输出-

The elements of list2 are : [20, 24, 30, 40, 44]

在这里,我们指定了 list1 的元素,然后使用 for 循环遍历每个元素,并使用模运算符检查它是否能被 2 整除。

在下面的程序中,我们使用列表推导式完成了相同的操作。

示例 - 2- 使用列表推导式

输出-

The elements obtained using list comprehension are : [20, 24, 30, 40, 44]

在这里,我们可以看到我们在 list2 中提供了推导式,其中我们在单行中使用了 for 循环和决策逻辑。

下一个程序是关于获取 list1 中所有元素的立方。

示例 - 3

输出-

The cube of the elements present in list1 is:  [8, 27, 64, 125, 216, 343, 512, 729, 1000]

我们使用了 append() 方法,并将每个元素的立方存储在 list2 中,然后将其显示出来。

我们可以使用列表推导式完成相同的事情:

示例 - 4- 使用列表推导式

输出-

The cube of the elements obtained by list comprehension is:  [8, 27, 64, 125, 216, 343, 512, 729, 1000]

字典推导式

我们都知道字典使用键值对,让我们来看看显示这些键值对的程序。

示例 -

输出-

The resultant dictionary would be:  {'Apple': 'Red', 'Bananas': 'Yellow', 'Custard Apple': 'Green', 'Pineapple': 'Brown', 'Blueberries': 'Violet'}

在下一个程序中,使用推导式实现了相同的功能。

示例 - 2- 使用字典推导式

输出-

The resultant dictionary using comprehension would be:  {'Apple': 'Red', 'Bananas': 'Yellow', 'Custard Apple': 'Green', 'Pineapple': 'Brown', 'Blueberries': 'Violet'}

在这里,我们可以看到我们在 **result_dict** 中提供了推导式,其中我们给出了从列表 fruits 和 color 中显示键值对的表达式。

集合推导式

集合用于显示给定集合中的唯一元素。让我们使用集合获取列表中所有元素的平方。

示例 - 1

输出-

The square of the numbers present in list1 is:  {64, 4, 36, 100, 9, 16, 49, 81, 25}

在下面的程序中,我们使用推导式完成了相同的事情。

示例 - 2- 使用集合推导式

输出-

The square of the numbers obtained through set comprehension:  {64, 4, 36, 100, 9, 16, 49, 81, 25}

我们从 list1 中获取了每个元素,并在 result_set 中提供了计算这些元素平方的表达式。

生成器推导式

生成器与函数非常相似。它使用 yield 关键字来生成值。让我们看看如何在生成器中使用推导式。

示例 -

输出-

The element which is even in list1 is:  12
The element which is even in list1 is:  16
The element which is even in list1 is:  20
The element which is even in list1 is:  24
The element which is even in list1 is:  28
The element which is even in list1 is:  30

执行程序后,它会显示 list1 中的偶数元素。


下一主题InfluxDB in Python