下面是代码示例:
from django.shortcuts import render_to_response
import MySQLdb
def book_list(request):
db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT name FROM books ORDER BY name')
names = [row[0] for row in cursor.fetchall()]
db.close()
return render_to_response('book_list.html', {'names': names})
尤其是:
names = [row[0] for row in cursor.fetchall()]
我只想知道,这行怎么写,我知道这是一种速记的方式,但有人能提供长版的样子吗?
最佳答案
那条线是alist comprehension。这是一个“长”版本。
names = []
for row in cursor.fetchall():
names.append(row[0])
关于python - 单行循环在Python中如何工作? [ list 理解],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15829509/