Python中的二进制数字字符串操作

时间:2018-11-29 20:21:53

标签: python string

如何在Python 3中计算字符串中1和0的(组)的唯一计数?例如

'11110000110110001111011'

输出应为

{0:{1, 3, 4} , 1:{2, 4}}

2 个答案:

答案 0 :(得分:0)

您可以使用itertools.groupby并将每个组的长度添加到一组字典中:

from itertools import groupby
s = '11110000110110001111011'
d = {}
for k, g in groupby(s):
    d.setdefault(int(k), set()).add(sum(1 for _ in g))

d变为:

{1: {2, 4}, 0: {1, 3, 4}}

答案 1 :(得分:0)

您可以使用while循环来实现此目的,方法是将与当前索引和idx相对的第一个字符的索引差添加到某个列表中,此处为counted_x的值。

x = '11110000110110001111011'
counted_x = {'0': [], '1': []}

idx = 0
while idx < len(x):
    oposite_key = str(abs(int(x[idx])-1))
    if oposite_key in x[idx:]:
        counted_x[x[idx]].append(x.index(oposite_key, idx) - idx)
    else:
        counted_x[x[idx]].append(len(x[idx:]))
    idx += counted_x[x[idx]][-1]

counted_x = [{k: list(set(v))} for k, v in counted_x.items()]
print(counted_x)

输出:

[{'0': [1, 3, 4]}, {'1': [2, 4]}]