0

我现在有一段很长的二进制代码,我如何计算给定段中 1 的位置,例如,我在下面给出了两个段:

seq1 = 10000000000000000000010000000000000000000010000000000000000000010000000000000000
       |                    |                    |                    |
       1                    22                   42                   58

seq2 = 10000000000000000000001000000000000000000001000000000000000000001000000000000000
       |                     |                    |                    |
       1                    23                    43                  59

第一个序列的输出应该是这样的:

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

对于第二个序列:

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

1 回答 1

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'))
于 2013-10-18T14:45:34.270 回答