【问题标题】:Spliting ones and zeros in binary with regex [duplicate]使用正则表达式在二进制中拆分 1 和 0 [重复]
【发布时间】:2021-01-23 16:06:34
【问题描述】:

我需要像这样在任何二进制表示中拆分 1 和 0。

code = 10001100
output_list = [1,000,11,00]

我找不到模式。 我正在使用 python3.x

【问题讨论】:

  • 你能分享你的正则表达式模式吗?

标签: python python-3.x regex split binary


【解决方案1】:

对于这个问题,你真的不需要正则表达式。您可以使用itertools 中的groupby 来执行此操作:

import itertools
code = "10001100"
gs = [list(g) for _, g in itertools.groupby(code)]

【讨论】:

    【解决方案2】:

    如果你想使用正则表达式,那么:

    import re
    code = r'10001100'
    output_list = re.findall(r'(0+|1+)', code)
    

    【讨论】:

      【解决方案3】:

      不需要正则表达式。这是pythonic的方法:

      code = '10001100'
      output_list = []
      interim_list = [code[i] + ',' if i != len(code)-1 and code[i] != code[i+1] else code[i] for i in range(len(code))]
      output_list.append(''.join(interim_list))
      print(output_list)
      
      >>> print(output_list)
      ['1,000,11,00']
      

      【讨论】:

        猜你喜欢
        • 2016-05-01
        • 2018-01-31
        • 1970-01-01
        • 2021-05-20
        • 2022-11-27
        • 2020-09-01
        • 1970-01-01
        • 2014-03-24
        • 1970-01-01
        相关资源
        最近更新 更多