如何从长0和1代码中计算出1的位置

时间:2013-10-18 14:43:35

标签: python binary

我现在有很长的二进制代码,如何在给定的拉伸中计算1的位置,例如我有两个延伸,如下所示:

seq1 = 10000000000000000000010000000000000000000010000000000000000000010000000000000000
       |                    |                    |                    |
       1                    22                   42                   58

seq2 = 10000000000000000000001000000000000000000001000000000000000000001000000000000000
       |                     |                    |                    |
       1                    23                    43                  59
对于第一个序列,

out put应该是这样的:

seq1 1:1 1:22 1:42 1:58

第二个序列:

seq2 2:1 2:23 2:43 2:59

1 个答案:

答案 0 :(得分:3)

这应该让你开始。

>>> s='10000000000000000000010000000000000000000010000000000000000000010000000000000000'
>>> [i+1 for i,ch in enumerate(s) if ch=='1']
[1, 22, 43, 64]
>>> 

如果你还需要休息,那就是:

def convertSeq(s, index):
    result = [i+1 for i,ch in enumerate(s) if ch=='1']
    result = ' '.join([str(index)+':'+str(i) for i in result])
    result = 'seq'+str(index)+' '+result
    return result

seq1 = '10000000000000000000010000000000000000000010000000000000000000010000000000000000'
seq2 = '10000000000000000000001000000000000000000001000000000000000000001000000000000000'

print convertSeq(seq1, 1)
print convertSeq(seq2, 2)

或者,如果您更喜欢单行:

def convertSeq(s, index):
    return 'seq{} {}'.format(
               index,
               ' '.join('{}:{}'.format(index, i+1)
                        for i,ch in enumerate(s)
                        if ch == '1'))