在python的Sequence中,如何根据长度划分字符串?

2024-06-01 11:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

>>>'mymedicinesarerighthere'

你需要用以下方式来分解这个词:

>>>['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

Tags: re方式edicineymsarermymedicinesarerighthereighthe
3条回答

代码

txt = "mymedicinesarerighthere"

i = 0
k = 1
myList = []
while i+k < len(txt):
  myList.append(txt[i:i+k])
  i += k
  k += 1
myList.append(txt[i: len(txt)])
print(myList)

输出

['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

这是一个相当干净的解决方案,使用了一些itertools

from itertools import count, islice

def chunks(s):
    i = iter(s)
    for n in count(1):
        chunk = ''.join(islice(i, n))
        if not chunk:
            return
        yield chunk

>>> list(chunks("mymedicinesarerighthere"))
['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

这是python生成器的版本

def gen(a):
    start=0
    step=1
    while a[start:start+step]:
        yield a[start:start+step]
        start+=step
        step+=1

list(gen('mymedicinesarerighthere'))
# ['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

这是另一种方法

您可以观察到每个切片的开始索引是0,1,3,6,10<在nthn-1th之间,他们的差异在于AP1,2,3,4,5

要得到分区的数量,必须解这个方程

=>(n*(n+1))/2=len(string)=>n^2+n-2*len(string)=0

使用math.ceil(n)获取n的ceil值将给出这里的分区数,当字符串长度为23时为7

import math
def start(n):
    return n*(n+1)//2
def findRoots(c):
    a=b=1
    d = b * b - 4 * a * c 
    sqrt_val = math.sqrt(abs(d))
    return math.ceil((-b + sqrt_val)/(2 * a))
out=[s[start(i-1):start(i-1)+i] for i in range(1,findRoots(-2*len(s))+1)]
# ['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

相关问题 更多 >