首页  >  文章  >  后端开发  >  Python 中的嵌套列表理解如何工作?

Python 中的嵌套列表理解如何工作?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 17:59:30527浏览

How Does Nested List Comprehension Work in Python?

理解嵌套列表理解

嵌套列表理解是Python 中的一个强大功能,可让您轻松创建复杂的数据结构。为了理解它是如何工作的,让我们看一个简化版本:

<code class="python">[(min([row[i] for row in rows]), 
max([row[i] for row in rows])) 
for i in range(len(rows[0]))]</code>

这个表达式相当于下面的 for 循环:

<code class="python">result=[]
for i in range(len(rows[0])):
  innerResult=[]
  for row in rows:
    innerResult.append(row[i])
  innerResult2=[]
  for row in rows:
    innerResult2.append(row[i])
  tuple=(min(innerResult), max(innerResult2))
  result.append(tuple)</code>

理解嵌套列表理解的关键是嵌套for 循环。外层循环迭代 rows[0] 的元素,而内层循环迭代 rows 中的行。

在上面的表达式中,第一个 for 循环负责创建列表的外部结构。对于每次迭代,它都会创建一个新元组。同时,第二个 for 循环创建元组的内部结构。对于 rows 中的每一行,它提取索引 i 处的元素并将其添加到内部结果列表中。

为了概括这个概念,任何形式的嵌套列表理解

<code class="python">[exp2([exp1 for x in xSet]) for y in ySet]</code>

都可以翻译成 for 循环结构:

<code class="python">result=[]
for y in ySet:
  innerResult =[]
  for x in xSet:
    innerResult.append(exp1)
  exp2Result = exp2(innerResult)
  result.append(exp2Result)</code>

对于更简单的情况,等价很简单:

  • [exp1 for x in xSet for y in ySet]: 等价于 for x in xSet: for y in ySet: result.append(exp1)
  • [[exp1 for x in xSet] for y in ySet]: 等价于 for y in ySet: innerResult=[];对于 xSet 中的 x:innerResult.append(exp1); result.append(innerResult)

以上是Python 中的嵌套列表理解如何工作?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn