我在python中使用函数map(),并将结果转换成一个列表,但结果是一个空列表

I use the function map() in python,and convert the results into a list,but the result is an empty list

为什么我在 python 中使用函数 map() 时得到一个错误的列表?这是我的代码,

当我使用 print() 函数打印 list(r) 时

print(list(r))

我的结果是一个空列表。

但是当我写代码的时候:

rList= list(r)

然后

print(rList)

我的结果是对的。

这是我的代码:

def f(x):
    return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
rList= list(r)
print( list(r) )
print( rList)

这是我的结果:

[]
[1,4,9,16,25,36,49,64,81]

这是预期的结果

[1,4,9,16,25,36,49,64,81]
[1,4,9,16,25,36,49,64,81]

当您将 r(地图对象)投射到列表时,这意味着您在整个列表中使用 运行 f 函数,它将完成。您不能两次使用 map 的结果。喜欢 itertools.groupby.