Explaining the list causes the error "name ... is not defined"

I have a list of integers called x

:

x = [3, 4, 5]

      

Now I want to create a new list of integers called y

where there is a sequence of x[0]

many 0's

followed by x[1]

lots 1's

followed by x[2]

many 2's

, etc.

In this example, this will give:

y = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]

      

My attempt was as follows:

y = [i for j in range(k) for (i,k) in enumerate(x)]

      

But this gives me an error:

name 'k' is not defined

      

What am I doing wrong and how can I do it with a list comprehension?

+3


source to share


2 answers


This helps you think about what you want to expand into regular loops for

:

r = []
for (i,k) in enumerate(x):
    for j in range(k):
        r.append(i)    

      

So the list comprehension becomes as follows:



[i for (i,k) in enumerate(x) for j in range(k)]

      

and keeping the same order.

+2


source


Your order is wrong

>>> x = [3,4,5]
>>> [i for (i,k) in enumerate(x) for j in range(k)]
[0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]

      



Refer the docs to exactly this line

List comprehension consists of parentheses containing an expression followed by a for clause, then zero or more for clauses or clauses.

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] 
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

      

+4


source







All Articles