我该如何转换这个代码:
注意:输出中缺少C和F,因为输入列表中对应的项为False。
[True, True, False, True, True, False, True]
转换为:
'AB DE G'
注意:输出中缺少C和F,因为输入列表中对应的项为False。
[True, True, False, True, True, False, True]
转换为:
'AB DE G'
假设你的布尔列表不太长:
bools = [True, True, False, True, True, False, True]
print ''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools))
>>> 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)
inputs = [True, True, False, True, True, False, True]
outputstring = ''.join(chr(65+i) if b else ' ' for i,b in enumerate(inputs))
这是基于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