Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am relatively new to the Python world from C#/Java. I love how the language makes many tasks simpler.

Here is my question:

display_val = []
for selected in boundfield.data:
  for circle in boundfield.field.queryset:
    if (selected==circle.id):
      display_val.append(circle.name)

Is there a more pythonic implementation that reduces the nested loops above?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

You might get a better result if you build a mapping (i.e. a dict) of one of the iterables.

To me it looks like you want all the circles that have an id that matches an id in boundfield.data.

You could do something like this:

for circle in boundfield.field.queryset:
    if circle.id in boundfield.data:
        display_val.append(circle.name)

This would also do an iteration, in the background, over the boundfield.data object. If you want to improve performance there, you could convert it to a Python data type has a fast look-up time, e.g. a set:

ids = set(boundfield.data)
for circle in boundfield.field.queryset:
    if circle.id in ids:
        display_val.append(circle.name)

Or, even better:

ids = set(boundfield.data)
display_val = [circle.name for circle in boundfield.field.queryset if circle in ids]

EDIT: If you like one-liners:

display_val = [circle.name for circle in boundfield.field.queryset if circle in boundfield.data]
share|improve this answer
    
Thanks Attila! You're awesome. That's exactly what I am looking for. Appreciate the multiple alternatives. –  tamakisquare Dec 9 '11 at 21:12
add comment

You can use list comprehension, which can be nested.

display_val = [circle.name for selected in boundfield.data\
    for circle in boundfield.field.queryset if selected == circle.id ]

See: http://www.python.org/dev/peps/pep-0202/

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.