Through a Django queryset call, I'm generating a list of integer tuples:
[(0,1),(0,2),(0,4),(5,8),.......]
I instead need to generate a list which sums the two elements inside the tuple together, ie
[1,2,4,13,.....]
How can I accomplish that within the Django queryset query?
The query I've written so far is:
photos_score_list = Photo.objects.filter(upload_time__gte=yesterday).annotate(unique_comments=Count('photocomment__submitted_by', distinct=True)).values_list('vote_score','unique_comments')
I don't know about Django, but when you have this:
l = [(0,1),(0,2),(0,4),(5,8)]
you can compute the sum of each element in one line using list comprehension:
l2 = [sum(x) for x in l]
result:
[1, 2, 4, 13]
applied to your problem:
photos_score_sum = [sum(x) for x in Photo.objects.filter(upload_time__gte=yesterday).annotate(unique_comments=Count('photocomment__submitted_by', distinct=True)).values_list('vote_score','unique_comments')]
Once you have that list of tuples, you can use a list comprehension to generate your second list like below:
>>> tuples_list = [(0,1),(0,2),(0,4),(5,8)]
>>> res_list = [i+j for i,j in tuples_list]
>>> res_list
[1, 2, 4, 13]
In our list comprehension, we return for tuple (i,j)
in tuples_list
the sum i+j
and the result is sorted in res_list
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.