python - Pythonic List Iteration -


i've got list of django querysets i'd combine single query. standard way of merging 2 querysets perform operation: newq = q1 | q2, , i'd perform operation on elements of list form single queryset object.

this pretty straightforward using loop, eg:

for qs in qs_list:     if final_qs not in locals():         final_qs = qs     else:         final_qs = final_qs | qs   

given wonders of python feels though there inbuilt function of kind you. however, had through itertools library , nothing jumped out way of simplifying operation.

so question is, there more pythonic way of performing above operation?

yes, function called functools.reduce(). use operator.or_():

import operator functools import reduce  final_qs = reduce(operator.or_, qs_list) 

reduce() takes first values of qs_list, passes first argument, operator.or_, executing qs_list[0] | qs_list[1]. takes result, plus next value in qs_list , applies first argument again, , on until qs_list done.

for qs_list 4 elements, comes down to:

or_(or_(or_(qs_list[0], qs_list[1]), qs_list[2]), qs_list[3]) 

or equivalent of:

qs_list[0] | qs_list[1] | qs_list[2] | qs_list[3] 

but reduce works length of qs_list > 0 (for list of length 1 first value returned without applying first argument).

note use of if final_qs not in locals() unpythonic; don't ever that. have written loop initial final_qs qs_list[0] instead:

final_qs = qs_list[0] qs in qs_list[1:]:     final_qs |= qs 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -