i have simple list splitting question:
given nested list this:
x = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]]
i want further split element(sub-list) longer 3, , length multiple of 3 or 3n+1 sub-lists of length 3, except last chunk, result want is:
x2 = [[1,4,3], [2,3,5],[1,3,52],[3,5,2,1],[2]]
i think can done itertools.groupby and/or yield functions... couldn't put details >> a_function(x)...
splits = [ a_function(x) if len(x)>3 , (len(x) % 3 == 0 or len(x) % 3 == 1) else x x in x]
could kindly give me pointers? much.
sometimes, when requirements list comprehension unusual or complicated, use generator function, so:
def gen(l): sublist in l: if len(sublist)%3 == 0: in range(0, len(sublist), 3): yield sublist[i:i+3] elif len(sublist)%3 == 1: in range(0, len(sublist)-4, 3): yield sublist[i:i+3] yield sublist[-4:] else: yield sublist # op's data: x = [[1,4,3],[2,3,5,1,3,52,3,5,2],[2]] y = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]] # using either list comprehension or list constructor: newx = [item item in gen(x)] newy = list(gen(y)) # result: assert newx == [[1, 4, 3], [2, 3, 5], [1, 3, 52], [3, 5, 2], [2]] assert newy == [[1, 4, 3], [2, 3, 5], [1, 3, 52], [3, 5, 2, 1], [2]]
Comments
Post a Comment