Splitting python list in chunks by element length

I see some great posts on how to break Python lists into pieces, such as how to break iterability in constant-sized pieces . Most posts are about splitting chunks or combining all the lines in a list together, and then a restriction based on regular slice routines.

However, I needed to do something similar based on the character limit. If you have a list of suggestions, but cannot cut off any fragments in the list.

I managed to run the code here:

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 

The result should return something like: Slices: [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20]] (Each number refers to an item in a list of strings)

So, when I iterate over this list of lists, I can use something like "" .join ([item for item in each]) to print 0,1,2,3,4,5,6 on one line, 7, 8,9,10,11,12,13 on the other. Sometimes a list can consist of only two elements, because each of these two elements is very long (it can be up to 380 characters or something else).

I know that the code is pretty bad and that I should use a generator. I just don't know how to do this.

Thanks.

+4
source share
2 answers

Something like this should work

 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) 

Also see textwrap

+3
source

This is just one liner. Hope he is helpful

 >>>list=[[1,2], [1]] >>>sorted(list, key=lambda sublist: len(sublist)) [[1], [1,2]] 

also:

 >>>list=[[1,2,3],[1],[1,2]] >>>sorted(list, key=lambda sublist: -len(sublist)) [[1,2,3], [1,2], [1]] 
+1
source

All Articles