简体   繁体   English

函数映射并在python3中减少

[英]the function map and reduce in python3

The return value of the map function in Python 3 is an Iterator . Python 3中map函数的返回值是Iterator

Why can the reduce function use the map result, when it needs an Iterable ? 为什么reduce函数在需要Iterable时可以使用map结果?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from functools import reduce
def fn(x, y):
  return x * 10 + y
def char2num(s):
   digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
   return digits[s]
reduce(fn, map(char2num, '13579'))

The reduce function can consume the iterator returned by map because an iterator is an iterable object. reduce函数可以使用map返回的迭代器,因为迭代器是一个可迭代的对象。 All iterators have an __iter__ method that returns the iterator itself. 所有迭代器都有一个__iter__方法,该方法返回迭代器本身。 That's all you need to be iterable (an __iter__ method that returns an iterator, though you can instead get by with a __getitem__ method in some cases). 这就是您需要可迭代的全部(返回迭代器的__iter__方法,尽管在某些情况下,您可以使用__getitem__方法进行迭代)。

That said, a few people will be careless of their terminology and use the term iterable when an iterator won't do (perhaps because they need to iterate on the same input several times). 就是说,当迭代器不使用时(可能是因为他们需要多次对同一个输入进行多次迭代),一些人会不小心使用术语“ 迭代” There's unfortunately not a single precise name for that subset of iterables (though sequence is often appropriate). 不幸的是,该可迭代子集并没有一个精确的名称(尽管顺序通常是适当的)。

The Python documentation is usually pretty good about this though. 不过,Python文档通常对此很好。 If it says a function expects an iterable, and iterator should always be acceptable. 如果说函数期望可迭代,则迭代器应始终可接受。 If a function or method needs to iterate over the input multiple times (as for instance, str.join does), it will build its own temporary sequence internally if the input isn't already of an acceptable type. 如果一个函数或方法需要多次遍历输入(例如str.join ),则如果输入不是可接受的类型,它将在内部建立自己的临时序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM