Python 中的理解示例

pythonserver side programmingprogramming更新于 2025/7/31 5:32:17

使用理解,您可以构造 Python 序列。在本文中,我们将了解如何创建和访问此类序列。

以下是 Python 中不同类型的理解。

  • 列表理解
  • 字典理解
  • 集合理解
  • 生成器理解

列表理解

我们可以通过多种方式创建列表并访问其中的元素。

使用 for 循环

示例

# 创建一个空列表
listA = []
# 将元素附加到列表
for n in range(4, 9):
   listA.append(n ** 3)
print("List using for loop:\n", listA)

输出

运行上述代码得到以下结果 −

List using for loop:
[64, 125, 216, 343, 512]

来自另一个列表

我们还可以通过直接将元素分配给新列表来从另​​一个列表创建列表。

示例

# 获取列表
listA = [12,9,32,45]
# 给定列表
print("给定列表:\n ",listA)
new_list = [n for n in listA if n % 3 == 0]
print("New List:\n", new_list)

输出

运行上述代码得到以下结果 −

给定列表:
[12, 9, 32, 45]
New List:
[12, 9, 45]

字典推导式

字典包含以对形式存在的元素,即键值对。在本文中,我们将了解如何创建此类字典。

使用 for 循环和 zip

我们可以接受两个可以包含键和值的列表。然后通过推导式将它们连接起来以创建一个新字典。

示例

Day = ['Mon', 'Tue', 'Wed',]
Time= ['2pm','10am','11am']
# 创建一个空字典
dictA = {}
# 使用 for 循环
for (key, value) in zip(Day, Time):
   dictA[key] = value
print("Dictionary using for loop:\n",dictA)

输出

运行上述代码得到以下结果 −

Dictionary using for loop:
{'Mon': '2pm', 'Tue': '10am', 'Wed': '11am'}

使用键作为索引

在本例中,我们采用 Python 列表并使用元素作为字典的键。还使用表达式导出每个键的值。

示例

listA = [3,5,4,8,9,2]
dictA = {}
# 使用 for 循环
for key in listA:
   if key % 2 != 0:
      dictA[key] = key ** 3
print("Dictionary using for loop:\n",dictA)

输出

运行上述代码得到以下结果 −

Dictionary using for loop:
{3: 27, 5: 125, 9: 729}

集合理解

Python 集合包含唯一元素。它可以以与列表类似的方式创建。

使用 for 循环

在这里,我们获取一个列表并应用条件从中获取一些元素。然后使用 add 方法将这些元素放入空集。

示例

listA = [12, 4, 25, 12,4,9]
setA = set()
# 使用 for 循环
for x in listA:
   if x % 3 == 0:
      setA.add(x)
print("Set using for loop:", setA)

输出

运行上述代码得到以下结果 −

Set using for loop: {9, 12}

使用 for 和 in

在此方法中,我们直接在 {} 内使用 for 循环。并将结果分配到集合中。在后续步骤中,我们使用列表中的元素。

示例

listA = [12, 4, 25, 12,4,9]
# 使用 for 循环
setA = {x for x in listA if x % 2 == 0}
print("Set using for loop:", setA)

输出

运行上述代码得到以下结果 −

Set using for loop: {12, 4}

生成器理解

在此方法中,我们从列表中获取元素并对它们应用某些条件,然后将它们放入 for 循环中。将结果赋值给序列。这种方法称为生成器理解。

示例

listA = [12, 4, 25, 12,4,9]
genrtr = (var for var in listA if var % 2 == 0)
print("Values using generator comprehensions:\n")
for x in genrtr:
   print(x, end=',')

输出

运行上述代码得到以下结果 −

Values using generator comprehensions:
12,4,12,4,

相关文章


有用资源