Discuss / Python / 疑问

疑问

Topic source

L

#1 Created at ... [Delete] [Delete and Lock User]

我在第一句和第二个语句之间加了第二句,为什么报错呀,网上也没找到解释,有大佬解释一下吗?

ns = map(str2num, ss)print(list(ns))return reduce(lambda acc, x: acc + x, ns)

西城

#2 Created at ... [Delete] [Delete and Lock User]

map函数返回的是迭代器,迭代器在list的时候相当于循环调用了next。reduce调用ns的时候,ns已经没有值可以next,所以reduce时会报错。

def fn(x):
    return x * x
r = map(fn,[1,2,3])
print(next(r))        # 此处打印 1
print(list(r))        # 认为打印[1,4,9],实际打印的结果是[4,9]
print(next(r))        # 此处会报StopIteration错误。
print(list(r))        # 此时打印的结果是[]。

  • 1

Reply