【问题标题】:how to split string by multi lengths?如何按多个长度分割字符串?
【发布时间】:2020-12-19 04:26:51
【问题描述】:

这是我的第一个问题。

例如: 我有这个字符串 === 294216673539910447 并有这个数字列表 === [3, 2, 3, 3, 2, 2, 3] 我需要输出 === [294, 21, 667, 353, 99, 10, 447]

我在表格中找到的所有内容都被 x 分割,但没有关于 multi x 的内容

【问题讨论】:

  • 欢迎来到 Stack Overflow,请告诉我们您的尝试。
  • 首先,我认为23是错误的。我假设输出应该是 21。我会给你一个提示。你需要一个循环。试一试,告诉我们你得到了什么。 :)

标签: python string list split


【解决方案1】:

试试这个:

def split(s, len_arr):
    res = []
    start = 0
    for part_len in len_arr:
        res.append(s[start:start+part_len])
        start += part_len
    return res

> split("294216673539910447", [3, 2, 3, 3, 2, 2, 3])
> ['294', '21', '667', '353', '99', '10', '447']

【讨论】:

    【解决方案2】:

    Python 中没有多重分割,所以这是一个自己实现它的好时机。

    我知道使用numpy 的功能性方法,我将尝试纯粹使用Python 重复相同的步骤:

    from itertools import accumulate
    s = '294216673539910447'
    numbers = [3, 2, 3, 3, 2, 2, 3]
    idx = list(accumulate(numbers, initial=0))
    print([s[i:j] for i,j in zip(idx[:-1], idx[1:])])
    

    这说明了一种应用累积和的绝妙方法。 accumulate 计算索引位置,它们是[0, 3, 5, 8, 11, 13, 15, 18]。所以你需要正确安排它们以获得切片0:33:5,...,15:18

    输出
    ['294', '21', '667', '353', '99', '10', '447']
    

    【讨论】:

      【解决方案3】:

      使用迭代器,并使用"".join() 连接它们,例如:

      def split(s, arr):
          iterator = iter(s)
          return ["".join(next(iterator) for _ in range(length)) for length in arr]
      
      print(split('294216673539910447', [3, 2, 3, 3, 2, 2, 3]))
      

      结果:

      ['294', '21', '667', '353', '99', '10', '447']
      

      【讨论】:

        【解决方案4】:

        我写了一个函数,可以灵活地使用不同类型的输入来做到这一点

        import itertools
        
        def splits(sequence, indexes, relative=False):
            """
            Split sequence at each index in "indexes".
        
            If "relative" is True, each index is taken as relative to the previous one.
        
            >>> list(splits('hello world', [3, 6]))
            ['hel', 'lo ', 'world']
            >>> list(splits('hello world', [3, 3], relative=True))
            ['hel', 'lo ', 'world']
            """
            if relative:
                indexes = itertools.accumulate(indexes)
            start = None
            for stop in itertools.chain(indexes, [None]):
                yield sequence[start:stop]
                start = stop  # For next loop
        

        在实践中:

        >>> list(splits('294216673539910447', [3, 2, 3, 3, 2, 2], True))
        ['294', '21', '667', '353', '99', '10', '447']
        

        请注意,您不需要输入列表中的最后一个索引。

        【讨论】:

          【解决方案5】:

          另一种方法是 - 转换为字符串并按索引拆分。

          在Python中,可以通过以下方式完成,

          number = str(294216673539910447)
          split = [3, 2, 3, 3, 2, 2, 3]
          count = 0
          result = []
          for s in split:
              result.append(int(number[count:s+count]))
              count += s
          print(result)
          

          给出输出:

          [294, 21, 667, 353, 99, 10, 447]
          

          【讨论】:

            猜你喜欢
            • 2023-03-17
            • 2019-03-14
            • 2020-12-22
            • 1970-01-01
            • 1970-01-01
            • 2021-09-25
            • 2020-08-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多