gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:10 24 4
gpt4 key购买 nike

我有一个整数列表,称为 x:

x = [3, 4, 5]

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

在这个例子中,这将给出:

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

关于python - 列表理解导致 "name ... is not defined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com