将一个字符串精确地分成N个片段 [英] Split a string into exactly N pieces

查看:84
本文介绍了将一个字符串精确地分成N个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数字N和一个字符串,我需要将字符串分成恰好 N个片段.

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

例如,如果N = 3

For example, if N=3

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

实现这一目标的最佳方法是什么(最好是在python中)?

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 )]

推荐答案

将输入序列分成偶数块的生成器:

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

这利用了 bool int True == 1 的子类的事实.

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

演示:

>>> 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']

这篇关于将一个字符串精确地分成N个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆