YNR
YNR

Reputation: 875

Iterating through two lists of objects Python

I have two long lists of objects in Python: queries_list (list of Query objects) and results_list (list of Result objects)

I'd like find Result objects that are related to a Query, using a common field 'search_id', then I should append related results to Query.results list.

The pseudocode is as below:

for q in  queries_list
   for r in results_list
       if q.search_id == r.search_id
           q.results.append(r)

Upvotes: 0

Views: 64

Answers (2)

avacariu
avacariu

Reputation: 2898

Your pseudo-code is almost Python. You're just missing colons:

for q in queries_list:
   for r in results_list:
       if q.search_id == r.search_id:
           q.results.append(r)

This is assuming your query objects already have results attributes.

If not, you can create them at runtime:

for q in queries_list:
   for r in results_list:
       if q.search_id == r.search_id:
           try:
               q.results.append(r)
           except AttributeError:
               q.results = [r]

Upvotes: 1

torkil
torkil

Reputation: 111

Your pseudocode is almost python-code, but here is a python variant using filter.

for query in queries_list:
   hasQueryId = lambda result: result.search_id == query.search_id
   query.results.extend(filter(hasQueryId, results_list))

This should result in all your queries result-lists being populated. This is still O(m*n), if you're looking for more efficient ways Id try sorting the results and queries by id.

Upvotes: 1

Related Questions