tags:

views:

124

answers:

5

How do I convert this:

[True, True, False, True, True, False, True]

Into this:

'AB DE G'

Note: C and F are missing in the output because the corresponding items in the input list are False.

+3  A: 
In [1]: ''.join(map(lambda b, c: c if b else ' ',
                    [True, True, False, True, True, False, True],
                    'ABCDEFG'))
Out[1]: 'AB DE G'
Michał Marczyk
+10  A: 

Assuming your list of booleans is not too long:

bools = [True, True, False, True, True, False, True]

print ''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools))
PreludeAndFugue
You can replace 65 with ord('A')
compie
Yes, ord('A') is clearer. Will change.
PreludeAndFugue
+1 Nice one. :)
Luiz Damim
+2  A: 
inputs = [True, True, False, True, True, False, True]
outputs = []
for i,b in enumerate(inputs):
  if b:
    outputs.append(chr(65+i)) # 65 = ord('A')
  else:
    outputs.append(' ')
outputstring = ''.join(outputs)

or the list comprehension version

inputs = [True, True, False, True, True, False, True]
outputstring = ''.join(chr(65+i) if b else ' ' for i,b in enumerate(inputs))
Amber
I would prefer enumerate(...) rather than range(len(...)).
PreludeAndFugue
Also, 97 -> 65 for uppercase letters :)
PreludeAndFugue
You're right, it's late and it slipped my mind. I've revised mine, but I also upvoted yours. :)
Amber
Thanks. It's early for me, so maybe I have an unfair advantage!
PreludeAndFugue
+9  A: 

You can use string.uppercase instead of chr/ord. This will give you locale-dependent results. For ascii you can use string.ascii_uppercase.

>>> import string
>>> bools = [True, True, False, True, True, False, True]
>>> ''.join(string.uppercase[i] if b else ' ' for i, b in enumerate(bools))

'AB DE G'
miles82
+1 for `string.uppercase`
Cristian Ciupitu
@miles: you don't need list comprehension there
SilentGhost
@SilentGhost: You're right, it's redundant. I've removed it now, thanks.
miles82
A: 

Here's generalized solution based on numpy.where():

#!/usr/bin/env python
import string, itertools

def where(selectors, x, y):
    return (xx if s else yy for xx, yy, s in itertools.izip(x, y, selectors))

condition = [True, True, False, True, True, False, True]
print ''.join(where(condition, string.uppercase, itertools.cycle(' ')))
# -> AB DE G

import numpy as np
print ''.join(np.where(condition, list(string.uppercase)[:len(condition)], ' '))
# -> AB DE G
J.F. Sebastian