列表理解导致 "name ... is not defined" 错误

List comprehension causes "name ... is not defined" error

我有一个整数列表,叫做 x:

x = [3, 4, 5]

我现在想创建一个新的整数列表,称为 y,其中有一系列 x[0]0's,然后是 x[1]1's,然后是 x[2] 很多 2's,等等...

在此示例中,这将给出:

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

我的尝试如下:

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

但这给了我错误:

name 'k' is not defined

我做错了什么,我怎样才能用列表理解来做到这一点?

您的顺序有误

>>> 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]

具体参考docs这一行

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if 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)]

考虑一下您想要扩展到常规 for 循环中的内容会有所帮助:

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

那么列表理解就变成了:

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

并保持相同的顺序。