我有一个字符串和二进制序列(它是 0 和 1 的整数)
sent1 = 'ERAGSJKDLLDERRR'
bin_seq = 100101010100011
所以我想通过与bin_seq
. 所以如果bin_seq
对应位置的值为1,它会返回字母。
所以它应该返回:
'EGJDLRR'
我itertools.compress
用于上述操作。
from itertools import compress
sent1 = 'ERAGSJKDLLDERRR'
bin_seq = 100101010100011
print("".join(list(itertools.compress(sent1, str(bin_seq)))))
返回输出:
'ERAGSJKDLLDERRR'
我知道我可以通过使用for
循环轻松做到这一点:
sent_new = []
for i,j in zip(sent1, str(bin_seq)):
if j == '1':
sent_new.append(i)
print("".join(sent_new))
但我更关心的是为什么它没有给出预期的输出itertools.compress
。
你的compress
方法很接近。它不起作用,因为字符串“0”和“1”在布尔上下文中都计算为 True。一种快速的解决方案是将它们转换为整数,因为在布尔上下文中 0 是 False 而 1 是 True:
import itertools
sent1 = 'ERAGSJKDLLDERRR'
bin_seq = 100101010100011
print("".join(itertools.compress(sent1, map(int, str(bin_seq)))))
结果:
EGJDLRR
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句