0

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)
2
  • 1
    It looks like you already have a working solution - what exactly is the question here? Are you looking for a better way? A faster/more efficient way? Commented Mar 22, 2015 at 0:23
  • Yes, I'm looking for a more efficient solution. Commented Mar 23, 2015 at 9:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.