Split a string into exactly N pieces

这一生的挚爱 提交于 2021-02-04 21:57:42

问题


Given a number N and a string, I need to split the string into exactly N pieces.

For example, if N=3

  • abcd -> ["ab", "c", "d"]
  • abcde -> ["ab", "cd", "e"]
  • abcdef -> ["ab", "cd", "ef"]
  • abcdefg -> ["abc", "de", "fg"]

What would be the best way to achieve this (preferably in python)?

My current (not working well enough) solution is

chunkSize = int(ceil(len(myString) / float(numOfChunks)))
chunks = [myString[i:i+chunkSize ] for i in range(0, len(myString), chunkSize )]

回答1:


A generator that divides an input sequence into even chunks:

def split_into(s, n):
    size, remainder = divmod(len(s), n)
    start = 0
    for i in range(n):
        length = size + (i < remainder)
        yield s[start:start + length]
        start += length

This uses the fact that bool is a subclass of int and True == 1.

Demo:

>>> list(split_into('abcd', 3))
['ab', 'c', 'd']
>>> list(split_into('abcde', 3))
['ab', 'cd', 'e']
>>> list(split_into('abcdef', 3))
['ab', 'cd', 'ef']
>>> list(split_into('abcdefg', 3))
['abc', 'de', 'fg']
>>> list(split_into('abcdefgh', 3))
['abc', 'def', 'gh']



回答2:


Here's the pseudocode. I don't know Python, but probably useful as a general purpose algorithm.

RegLen <- Int(Len(Str)/N)   # The integer portion only
FirstLen = Len(Str) - N * RegLen
# Output goes into Output[] array of length N elements, each a substring

Output[1] = Left(Str, FirstLen)

For i <- 2 to N
   StartPosition <- FirstLen + (i-2) * RegLen + 1
   Output[i] <- Mid(Str, StartPosition, RegLen)
Loop


来源:https://stackoverflow.com/questions/24650971/split-a-string-into-exactly-n-pieces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!