Single line set for nearly redundant lists

Consider two comprehensions of a list gammaand deltawith almost redundant code. The difference is in the sliced ​​lists alphaand 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 one insert (say gamma,delta = ...)?

I have several other code snippets that are similar in nature, and I would like to simplify code redundancy.

+4
source share
4 answers

As for your question related to combining the expression of the expression described above, you can get gammaand deltausing with a single list comprehension like: zip

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

, , zip:

>>> zip(*[(i, i+1) for i in range(0, 10, 2)])
[(0, 2, 4, 6, 8), (1, 3, 5, 7, 9)]

:

>>> [(i, i+1) for i in range(0, 10, 2)]
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

* zip, :

>>> zip(*[(i, i+1) for i in range(0, 10, 2)])
[(0, 2, 4, 6, 8), (1, 3, 5, 7, 9)]

, , , " ?"

+4

list-comprehensions , . , , , lists, chunking, .

function, list, chunk gamma delta.

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

gamma, delta = chunk(gamma), chunk(delta)
+8

Another way ...

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

This is slightly faster than the zip solution made:

genny 3.439506340350704
zippy 4.3039169818228515

the code:

from timeit import timeit
alpha = list(range(60000))
beta = list(range(60000))
def genny():
    gamma, delta = ([src[i:i+30] for i in range(0,49980,30)] for src in (alpha, beta))
def zippy():
    gamma, delta = zip(*[(alpha[i:i+30], beta[i:i+30]) for i in range(0,50000,30)])
n = 1000
print('genny', timeit(genny, number=n))
print('zippy', timeit(zippy, number=n))
+1
source

You can express lambda:

g = lambda l: [l[i:i+30] for i in range(0,50000, 30)]
gamma, delta = g(alpha), g(beta)
0
source

Source: https://habr.com/ru/post/1691561/


All Articles