python – 功能风格的Conjoin功能
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 功能风格的Conjoin功能,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2476字,纯文字阅读大概需要4分钟。
内容图文
![python – 功能风格的Conjoin功能](/upload/InfoBanner/zyjiaocheng/823/4ffb69ec7c7748e68ebf3f10f54421ed.jpg)
最近,在阅读Python “Functional Programming HOWTO”时,我遇到了一个提到test_generators.py标准模块,在那里我找到了以下生成器:
# conjoin is a simple backtracking generator, named in honor of Icon's
# "conjunction" control structure. Pass a list of no-argument functions
# that return iterable objects. Easiest to explain by example: assume the
# function list [x, y, z] is passed. Then conjoin acts like:
#
# def g():
# values = [None] * 3
# for values[0] in x():
# for values[1] in y():
# for values[2] in z():
# yield values
#
# So some 3-lists of values *may* be generated, each time we successfully
# get into the innermost loop. If an iterator fails (is exhausted) before
# then, it "backtracks" to get the next value from the nearest enclosing
# iterator (the one "to the left"), and starts all over again at the next
# slot (pumps a fresh iterator). Of course this is most useful when the
# iterators have side-effects, so that which values *can* be generated at
# each slot depend on the values iterated at previous slots.
def simple_conjoin(gs):
values = [None] * len(gs)
def gen(i):
if i >= len(gs):
yield values
else:
for values[i] in gs[i]():
for x in gen(i+1):
yield x
for x in gen(0):
yield x
我花了一段时间才明白它是如何工作的.它使用可变列表值来存储迭代器的结果,而N 1迭代器返回值,它们遍历迭代器的整个链.
当我在阅读函数式编程时偶然发现这段代码时,我开始思考是否可以使用函数式编程重写这个连接生成器(使用itertools module中的函数).
有很多以函数式编写的例程(只需看一下食谱部分的this文章末尾).
但是,遗憾的是,我还没有找到任何解决方案.
那么,是否可以使用itertools module使用函数式编程来编写这个连接发生器?
谢谢
解决方法:
这似乎工作,它仍然是懒惰的:
def conjoin(gs):
return [()] if not gs else (
(val,) + suffix for val in gs[0]() for suffix in conjoin(gs[1:])
)
def range3():
return range(3)
print list(conjoin([range3, range3]))
输出:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
显示可变状态的示例用法:
x = ""
def mutablerange():
global x
x += "x"
return [x + str(i) for i in range(3)]
print list(conjoin([range3, mutablerange]))
输出:(观看越来越多的’x’)
[(0, 'x0'), (0, 'x1'), (0, 'x2'), (1, 'xx0'), (1, 'xx1'), (1, 'xx2'), (2, 'xxx0'), (2, 'xxx1'), (2, 'xxx2')]
如果我们使用itertools.product:
x = ""
print list(itertools.product(range3(), mutablerange()))
结果如下:
[(0, 'x0'), (0, 'x1'), (0, 'x2'), (1, 'x0'), (1, 'x1'), (1, 'x2'), (2, 'x0'), (2, 'x1'), (2, 'x2')]
因此,有人清楚地看到,itertools.product缓存了迭代器返回的值.
内容总结
以上是互联网集市为您收集整理的python – 功能风格的Conjoin功能全部内容,希望文章能够帮你解决python – 功能风格的Conjoin功能所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。