Python 或 Django 中的 For 循环之前的主体?

css*_*bie 2 python django

来自 Django 示例,

latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question_text for p in latest_question_list])
Run Code Online (Sandbox Code Playgroud)

为什么p.questionfor循环之前?

Par*_*us- 5

Python 支持一个称为列表推导式的概念。它可以用来以一种非常自然、简单的方式构建列表,就像数学家所做的那样。

\n\n

以下是数学中描述列表(或集合、元组或向量)的常见方法。

\n\n
S = {x\xc2\xb2 : x in {0 ... 9}}\nV = (1, 2, 4, 8, ..., 2\xc2\xb9\xc2\xb2)\nM = {x | x in S and x even}\n
Run Code Online (Sandbox Code Playgroud)\n\n

您可能从数学中知道了上述内容。在 Python 中,您几乎可以像数学家一样编写这些表达式,而无需记住任何特殊的神秘语法。

\n\n

这是在 Python 中执行上述操作的方法:

\n\n
>>> S = [x**2 for x in range(10)]\n>>> V = [2**i for i in range(13)]\n>>> M = [x for x in S if x % 2 == 0]\n>>> \n>>> print S; print V; print M\n[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]\n[0, 4, 16, 36, 64]\n
Run Code Online (Sandbox Code Playgroud)\n\n

在此处阅读有关列表理解的更多信息。

\n