根据项长度将Python列表分块
我看到这里有一些很棒的帖子,讲的是如何把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 = 0 + itemlength
tmpslices.append(i)
if i==len(stringlist)-1:
slices.append(tmpslices)
return slices
输出应该是这样的: Slices is: [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20]] (每个数字代表字符串列表中的一个项目)
所以,当我遍历这个列表的列表时,我可以用类似“".join([item for item in each])”的方式来打印出0,1,2,3,4,5,6在一行,7,8,9,10,11,12,13在另一行。有时候,一个列表可能只有2个项目,因为这两个项目都很长(加起来不会超过380个字符或其他限制)。
我知道我的代码写得很糟糕,我应该使用生成器,但我不太确定该怎么做。
谢谢。
2 个回答
1
这只是一个简单的一行代码。希望对你有帮助。
>>>list=[[1,2], [1]]
>>>sorted(list, key=lambda sublist: len(sublist))
[[1], [1,2]]
另外:
>>>list=[[1,2,3],[1],[1,2]]
>>>sorted(list, key=lambda sublist: -len(sublist))
[[1,2,3], [1,2], [1]]
4
像这样应该可以工作
def _splicegen(maxchars, stringlist):
"""
Return a list of slices to print based on maxchars string-length boundary.
"""
runningcount = 0 # start at 0
tmpslice = [] # tmp list where we append slice numbers.
for i, item in enumerate(stringlist):
runningcount += len(item)
if runningcount <= int(maxchars):
tmpslice.append(i)
else:
yield tmpslice
tmpslice = [i]
runningcount = len(item)
yield(tmpslice)
另外,可以看看这个 textwrap 模块