【问题标题】:What is a for-loop with the for-loop at the end of it called in python? [duplicate]什么是在python中调用的for循环末尾的for循环? [复制]
【发布时间】:2019-02-20 23:56:42
【问题描述】:

我见过一些python代码的sn-ps,其中循环编写如下:

someList = g.db.execute('SELECT title, body FROM posts')
posts = [dict(title=x[0],body=[1]) for x in someList.fetchAll()]

这种循环称为什么?

我意识到它可能只是被称为 for 循环,但它的语法与基于 c 的语言完全不同(更短且更高效),所以我只是想知道是否有其他类似这样的名称。

【问题讨论】:

  • 这是一个列表理解。
  • 请注意它绝对不是一个循环,而是一个单独的表达式,称为list comprehension
  • 一般情况下,我看到这种类型在理解下循环,例如列表理解或集合理解。

标签: python


【解决方案1】:

在 Python 中称为list comprehension

【讨论】:

    【解决方案2】:

    这是列表推导,它们是等价的:

    [dict(title=x[0],body=[1]) for x in someList]
    
    for x in someList:
        dict(title = x[0], body = [1])
    

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 2012-11-02
      • 2013-01-04
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多