我曾多次认为生成器样式可以比返回列表更直接,例如,
def foo(input_array):
for x in input_array:
yield processed(x)
对比
def bar(input_array):
accumulator = []
for x in input_array:
accumulator.append(processed(x))
return accumulator
(好吧,如果真的那么简单,我会写 map
,但你明白了:生成器版本更简洁)。但是,生成器的返回类型并不总是需要的。是否有内置装饰器可用于将 foo
更改为返回列表或元组的函数?我自己写的方式是,
import functools
def transform_return_value(transformer):
def inner(f):
@functools.wraps(f)
def new_f(*argv, **kwargs):
return transformer(f(*argv, **kwargs))
return new_f
return inner
@transform_return_value(list)
def foo(input_array):
for x in input_array:
yield processed(x)
最佳答案
据我所知(我已经看过,因为我想知道完全相同的东西),不:没有直接的方法可以使用标准库执行此操作。
在 unstdlib.py 库中有一个经过彻底测试的 listify
包装器,但是:https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149
def listify(fn=None, wrapper=list):
"""
A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
... for i in iterable:
... yield len(i)
>>> get_lengths(["spam", "eggs"])
[4, 4]
>>>
>>> @listify(wrapper=tuple)
... def get_lengths_tuple(iterable):
... for i in iterable:
... yield len(i)
>>> get_lengths_tuple(["foo", "bar"])
(3, 3)
"""
def listify_return(fn):
@wraps(fn)
def listify_helper(*args, **kw):
return wrapper(fn(*args, **kw))
return listify_helper
if fn is None:
return listify_return
return listify_return(fn)
关于python - Python中是否有一个库函数可以将生成器函数转换为返回列表的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12377013/