【问题标题】:I use the function map() in python,and convert the results into a list,but the result is an empty list [duplicate]我在python中使用函数map(),并将结果转换为列表,但结果是一个空列表[重复]
【发布时间】:2019-06-04 02:20:20
【问题描述】:

为什么我在 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]

【问题讨论】:

标签: python list dictionary printing mapreduce


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2016-12-28
  • 2018-02-04
  • 2018-11-20
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
相关资源
最近更新 更多