0
我目前正在優化我的一些項目中的代碼,並發現一些非常慢的代碼。我有一個通過Django查詢獲得的對象列表。我想過濾這個列表並只返回一個對象,因爲這些值是唯一的。從Django模型對象列表中過濾對象的最佳方法
questions = set(Question.object.all())
choices = set(Choice.objects.select_related('question').filter(question__in=questions).all())
for question in questions:
Answer(question=question,
choice=next(filter(lambda x: x.question == question), choices)),
response=response)
其中一些只是僞代碼,但真正的問題是在next()函數中。有沒有更快的方法來查找一組中的元素?使用列表理解是無可爭議的,因爲它解析整個列表並返回所有元素。 Filter是一個生成器,next()返回它找到的第一個值。
我使用Django 1.7和Python 3.4
謝謝!
謝謝!加快了很多。 – 2015-03-19 12:28:17