D
D
darke3v2013-12-05 12:37:04
Python
darke3v, 2013-12-05 12:37:04

List comprehension problem

The idea is that every three characters from, a number from id was added to the secretkey variable.
It turned out like this:

secretkey='abcdef'
id='12'
test=[secretkey[i:i + 3]+l for i in range(0, len(secretkey), 3) for l in id]
['abc1', 'abc2', 'def1', 'def2']

How to get rid of the second cycle in order to avoid dubbing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iley, 2013-12-05
@darke3v

You can decide, for example, like this:

from itertools import cycle
test = [secretkey[i:i + 3]+l for i, l in zip(range(0, len(secretkey), 3), cycle(id))]

But, in my opinion, the code will be more readable if you add a helper function that splits the string (or any other sequence) into equal parts:
from itertools import cycle

def chunks(l, n):
    """ Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

test = [ chunk + number
         for chunk, number in zip(chunks(secretkey, 3), cycle(id)) ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question