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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With