我在这里看到一些关于如何将Python列表拆分成块的好帖子,比如如何在常量大小的块中拆分可迭代的块.大多数帖子涉及分割块或将列表中的所有字符串连接在一起,然后根据正常的片段例程进行限制.
但是,我需要根据字符限制执行类似的操作.如果您有一个句子列表但不能截断列表中的任何切片.
我能够在这里制作一些代码:
def _splicegen(maxchars, stringlist):
"""
Return a list of slices to print based on maxchars string-length boundary.
"""
count = 0 # start at 0
slices = [] # master list to append slices to.
tmpslices = [] # tmp list where we append slice numbers.
for i, each in enumerate(stringlist):
itemlength = len(each)
runningcount = count + itemlength
if runningcount < int(maxchars):
count = runningcount
tmpslices.append(i)
elif runningcount > int(maxchars):
slices.append(tmpslices)
tmpslices = []
count …Run Code Online (Sandbox Code Playgroud)