当前位置: 动力学知识库 > 问答 > 编程问答 >

python - django are set operations faster or for loop?

问题描述:

Which of the following operations are faster?

Using for loop:

 OrgIdChoices = []

Orgid_used_choices = [(choice["organization_id"])for choice in list(Organization.objects.all().values("organization_id"))] #Gets used ID's

OrgIdAvailChoices = [ "%c%c" % (x, y) for x in range(ord('A'), ord('Z')+1) for y in range(ord('A'), ord('Z')+1)] #Gets available ID's

for i in OrgIdAvailChoices:

if not i in Orgid_used_choices:

OrgIdChoices.append((i,i)) #Generates OrgIdAvailChoices which are not in Orgid_used_choices

OR using set operation:

 OrgIdChoices = []

Orgid_used_choices = set([(choice["organization_id"])for choice in list(Organization.objects.all().values("organization_id"))])

OrgIdAvailChoices = set([ "%c%c" % (x, y) for x in range(ord('A'), ord('Z')+1) for y in range(ord('A'), ord('Z')+1)])

OrgChoices = OrgIdAvailChoices - Orgid_used_choices

for i in OrgChoices:

OrgIdChoices.append((i,i))

网友答案:

Have a look at the QuerySet API documentation, more precisely the values_list part (with flat=True) and the distinct() part. Surely this will be faster than the values, extracting the field you want and converting to list or set approach.

After that a simple approach as generating the set OrgIdAvailChoices and difference_update with the QuerySet should be quite faster than your proposed one.

Alternatively, inspired by Pannu's comment, an approach with itertools:

import itertools
import string

filter(
    lambda x: x not in OrgIdAvailChoices,
    [''.join(el) for el in itertools.combinations_with_replacement(string.ascii_uppercase, 2)]
)

To tell the truth, I'm not certain if QuerySet is actually a set, that is if search in it are logarithmic, but judging by my experience the proper usage of Django's ORM (as described in the beginning of my answer) will bring you the greatest speedup.

分享给朋友:
您可能感兴趣的文章:
随机阅读: