Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner for nearly redundant list comprehensions

Consider two list comprehensions gamma and delta with nearly redundant code. The difference being the sliced lists alpha and beta, namely

gamma = [alpha[i:i+30] for i in range(0,49980,30)]
delta = [beta[i:i+30] for i in range(0,49980,30)]

Is there a pythonic way to write this as a one liner (say gamma,delta = ... )?

I have a few other pieces of code that are similar in nature, and I'd like to simplify the code's seeming redundancy.

like image 748
sunspots Avatar asked Dec 10 '22 08:12

sunspots


1 Answers

Although one-line list-comprehensions are really useful, they aren't always the best choice. So here since you're doing the same chunking to both lists, if you wanted to change the chunking, you would have to modify both lines.

Instead, we could use a function that would chunk any given list and then use a one-line assignment to chunk gamma and delta.

def chunk(l):
    return [l[i:i+30] for i in range(0, len(l), 30)]

gamma, delta = chunk(gamma), chunk(delta)
like image 192
Joe Iddon Avatar answered Dec 12 '22 20:12

Joe Iddon