Login

assigning many partially deviant variables

Author:
justinlilly
Posted:
June 5, 2007
Language:
Python
Version:
.96
Tags:
assignment variable for-loop
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

Comments

Please login first before commenting.