python - 在位串的左侧和右侧填充数字的字典

标签 python

我有一个像这样的位串:1101100111 我想构造一个字典,其中包含任意零左边的个数和右边的个数,例如:

left = {2: 2, 5: 2, 6: 0}, right = {2: 2, 5: 0, 6: 3}

在这些字典中,键是索引,值是索引的个数。 所以在索引 2 处,左边有 2 个,右边有 2 个。 在索引 5 处,左边有 2 个,右边有 0 个。 在索引 6 处,左边有 0 个,右边有 3 个。

我有这个代码:

    left, right, zeroes = {}, {}, []
    last_zero, last_one = 0, 0

    for i, v in enumerate(nums):
        if v == 0:
            left[i] = i - last_zero
            last_zero = i + 1
            zeroes.append(i)
        else:
            last_one = i

    print('left', left)
    print('right', right)

我可以通过“破解”来填充“左”字典,但填充“右”字典是个问题。

最佳答案

这是构建逻辑的一种方式。

var = str(1101100111)

idx = [i for i, j in enumerate(var) if j=='0']
counts = list(map(len, var.split('0')))

left = dict(zip(idx, counts))        # {2: 2, 5: 2, 6: 0}
right = dict(zip(idx, counts[1:]))   # {2: 2, 5: 0, 6: 3}

解释

  • 将你的序列转换为字符串;并找到“0”个元素的索引。
  • 按“0”拆分并提取每个“1”序列的长度。
  • 最后,使用 dict(zip(x, y)) 创建左右字典。

关于python - 在位串的左侧和右侧填充数字的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49470141/

相关文章:

python - django.db.utils.DataError : numeric field overflow - django 错误

python - 在 Django 中,如何确定给定文本的翻译是否可用?

python - selenium.common.exceptions.WebDriverException : Message: 'chromedriver' executable needs to be in PATH

python - 不同概率数据的平均值

python - 对于这个重复的片段代码模式更好的 pythonic 习语

python - 如何在数据框列中过滤并仅保留 6 位数字

python - keras multiple_gpu_model 导致 "Can' t pickle 模块对象“错误

python - 用于 pickled pandas 数据输入的 tensorflow 管道

python - 使用时间、日期、timedelta

MATLAB 函数 findchangepts 的 Python 等价物