- Author:
 - justinlilly
 - Posted:
 - June 5, 2007
 - Language:
 - Python
 - Version:
 - .96
 - Score:
 - -1 (after 3 ratings)
 
This was a much better way of incrementing variables that only changed a small amount in name. deltab in #python also said I could have used tuples, but I'm not familiar with them yet, so I added this to a list of things to look into.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33  | # Good Code:
for item_obj in todo_list.item_set.all():
    todo_dict['importance_%d_%s' % (item_obj.importance, 'complete' if item_obj.completed else 'incomplete')] += 1
# My original code was a collection of ifs:
       for item_obj in todo_list.item_set.all():
            if item_obj.importance == 1:
                if item_obj.completed == True:
                    todo_dict['importance_1_complete'] += 1
                else
                    todo_dict['importance_1_incomplete'] += 1
            if item_obj.importance == 2:
                if item_obj.completed == True:
                    todo_dict['importance_2_complete'] += 1
                else
                    todo_dict['importance_2_incomplete'] += 1
            if item_obj.importance == 3:
                if item_obj.completed == True:
                    todo_dict['importance_3_complete'] += 1
                else
                    todo_dict['importance_3_incomplete'] += 1
            if item_obj.importance == 4:
                if item_obj.completed == True:
                    todo_dict['importance_4_complete'] += 1
                else
                    todo_dict['importance_4_incomplete'] += 1
            if item_obj.importance == 5:
                if item_obj.completed == True:
                    todo_dict['importance_5_complete'] += 1
                else
                    todo_dict['importance_5_incomplete'] += 1
 | 
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.