map
和 filter
通常可以与列表理解互换,但是 reduce
不像 map
那样容易换掉> 和 filter
(此外,在某些情况下我仍然更喜欢函数式语法)。但是,当您需要对参数本身进行操作时,我发现自己经历了句法体操,最终不得不编写整个函数以保持可读性。
我将使用 map
来简化插图单元测试,但请记住,现实生活中的用例可能更难表达为列表理解。
我找到了两种乱七八糟的方法来解决这个问题,但我从来没有真正使用过。
[afunc(*i) for i in aniter] == map(afunc, *zip(*aniter))
[afunc(*i) for i in aniter] == map(lambda i: apply(afunc, i), aniter)
是否有任何简洁、优雅的方式来表达这些表达式的右侧?
最佳答案
查看 itertools寻找能让您的生活更轻松的工具。
例如,您发布的代码已经可用为 itertools.starmap
.
itertools.starmap(afunc, aniter)
来自文档:
Make an iterator that computes the function using arguments obtained from the iterable. Used instead of imap() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between imap() and starmap() parallels the distinction between function(a,b) and function(*c). Equivalent to:
def starmap(function, iterable): # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 for args in iterable: yield function(*args)
itertools
中还隐藏了很多其他好东西,所以我建议您通读文档,看看是否还有其他可以使用的东西。 recipes本节还展示了如何使用 itertools
中可用的函数来解决各种问题。即使您找不到满足您确切要求的方法,您也可以将展示的一些想法用作灵感来源。
关于python - 您可以将操作直接应用于 map/reduce/filter 中的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11402607/