3

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

4 回答 4

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])
于 2013-05-22T22:13:33.180 回答
1

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]
于 2013-05-22T22:13:08.400 回答
1

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
于 2013-05-22T22:15:17.220 回答
0
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
于 2013-05-22T22:21:55.693 回答