I have a series of checkboxes with simple values (a, b, c, etc.) that when checked, would "trigger" a string of text to appear. The problem is that I will have a great number of checkboxes, and manually repeating my code below for each checkbox is going to be a mess. I am still learning Python and am struggling with creating a loop to make this happen.
Here is my current (working, but undesirable) code:
if a:
a = 'foo'
if b:
b = 'bar'
...
My attempt at the loop, which returns box as nothing:
boxes = [a, b, c, ...]
texta = 'foo'
textb = 'bar'
...
for box in boxes:
if box:
box = ('text=%s', box)
What should I do to get my loop functioning properly? Thanks!
4 Answers 4
How about:
mydict = {a:'foo', b:'bar', c:'spam', d:'eggs'}
boxes = [a, b, c]
for box in boxes:
print('text=%s' % mydict[box])
Comments
That won't work, you're just assigning to the local variable in the loop, not to the actual position in the list. Try this:
boxes = [a, b, c, ...] # boxes and texts have the same length
texts = ['texta', 'textb', 'textc', ...] # and the elements in both lists match
for i in range(len(boxes)):
if boxes[i]:
boxes[i] = texts[i]
1 Comment
for box, text in zip(boxes, texts):You should use zip() and enumerate() here:
boxes = [a, b, c, ...]
texts = ['texta', 'textb', 'textc', ...]
for i,(x,y) in enumerate(zip(boxes,texts)):
if x:
boxes[i] = y
Comments
a,b,c = (1,0,11)
boxes = {a:'foo', b:'bar', c:'baz'}
for b in ["text=%s" % boxes[b] for b in boxes if b]:
print b