Question

I was just playing with list comprehensions and came across this :

h = [ b for b in range(1, 9) for k in range(b, b*10) if k%2==0 for j in range(2*k, k*k)]

Expected Result:

h = [1, 2, 3, 4, 5, 6, 7, 8]

Actual Result is not as expected, contains len(h) = 196000 items.

Please explain how this works ?

Était-ce utile?

La solution

Why do you think this is the expected result?

Your code is equivalent to:

h = []
for b in range(1, 9):
    for k in range(b, b*10):
        if k%2==0:
            for j in range(2*k, k*k):
                h.append(b)

So, for each number from 1 to 8, it will append it many times to the list

You can also see how many times each number is added with the help of groupby:

>>> for i,j in itertools.groupby(h):
    print(i, sum(1 for i in j))

1 80
2 960
3 3640
4 9120
5 18392
6 32472
7 52328
8 79008

Autres conseils

Your list comp is equivalent to this:

h = []
for b in range(1, 9):
    for k in range(b, b * 10):
        if k % 2 == 0:
            for j in range(2 * k, k * k):
                h.append(b)

So probably it is simply your understanding of the order of the loops in a nested list comprehension was wrong.

Mentally expand the loops in the same order they appear in the comprehension (or avoid triple nested comprehensions altogether - they have a habit of becoming incomprehensible!).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top