在哪里可以学习这个Python括号运算符?

3 投票
5 回答
3381 浏览
提问于 2025-04-17 09:16

最近我在看Flask,在他们的用户指南中发现了下面这段Python代码:

@app.route('/')
def show_entries():
    cur = g.db.execute('select title, text from entries order by id desc')
    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    return render_template('show_entries.html', entries=entries)

这里

entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]

从数据库中创建了一个条目列表。这是我第一次知道可以在括号里面用循环来生成一个列表。

有没有人能告诉我在哪里可以找到这种语法的官方介绍?这种写法是只适用于列表,还是也适用于元组或者其他东西呢?

非常感谢!

5 个回答

1

这叫做列表推导式,下面有一个链接可以查看Python的官方文档。

http://docs.python.org/tutorial/datastructures.html#list-comprehensions

还有一些更多的例子:

http://www.secnetix.de/olli/Python/list_comprehensions.hawk

3

这个东西叫做列表推导式

我觉得这应该是官方文档:http://docs.python.org/tutorial/datastructures.html#list-comprehensions

撰写回答