I wasn’t able to figure out exactly what you were looking for from your post, but here’s what I think you want:
Given a list, get all the numbers at even indices. If any of these numbers are even, put them in a new list and return it:
In [10]: L = [3,1,54,5,2,3,4,5,6,5,2,5,3,2,5,2,2,5,2,5,2]
In [11]: [num for i,num in enumerate(L) if not num%2 and not i%2]
Out[11]: [54, 2, 4, 6, 2, 2, 2, 2]
If you want to add 0
s in between, then you can do a little itertools
magic:
In [12]: list(itertools.chain.from_iterable(zip((num for i,num in enumerate(L) if not num%2 and not i%2), itertools.cycle([0]))))[:-1]
Out[12]: [54, 0, 2, 0, 4, 0, 6, 0, 2, 0, 2, 0, 2, 0, 2]
Ok, that was a lot of brackets and parentheses, so let’s take a closer look at it:
-
list(...)[:-1]
converts...
into alist
and gets all but the last element of that list. This is similar to what you were trying to do when you added0
s and removed the last one -
(num for i,num in enumerate(L) if not num%2 and not i%2)
is the same as what it was before the edit, except that it uses parentheses (()
) instead of brackets ([]
). This turns it into a generator-comprehension, as opposed to a list comprehension – it only matters in that it performs a little bit of optimization – the values are not computed until they are needed (untilzip
asks for the next value) -
itertools.cycle([0])
gives an endless list of0
s -
zip(A, B)
returns a list of tuples, in which thei
th tuple has two elements – thei
th element ofA
, and thei
th element ofB
-
itertools.chain.from_iterable(zip(A, B))
returns the elements ofA
andB
interleaved, as a generator. In essence, it’s like doing this:
def someFunc(A, B): for i in range(len(A)): yield A[i] yield B[i]
Thus, all of these put together give you exactly what you want
2
solved List of even numbers at even number indexes using list comprehension [closed]