Login

assigning many partially deviant variables

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.