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.
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))
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'
In [1]: ''.join(map(lambda b, c: c if b else ' ',
[True, True, False, True, True, False, True],
'ABCDEFG'))
Out[1]: 'AB DE G'
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))
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
精彩评论