所有子集的集合
在 Python2 中,我可以用来
def subsets(mySet):
return reduce(lambda z, x: z + [y + [x] for y in z], mySet, [[]])
查找 mySet
的所有子集。 Python 3 已删除reduce
。
对于 Python3 来说,同样简洁的重写是什么?
In Python2 I could use
def subsets(mySet):
return reduce(lambda z, x: z + [y + [x] for y in z], mySet, [[]])
to find all subsets of mySet
. Python 3 has removed reduce
.
What would be an equally concise rewrite of this for Python3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面是 Python 中幂集(所有子集的集合)算法的几种可能实现的列表。有些是递归的,有些是迭代的,有些不使用
reduce
。有很多选项可供选择!Here's a list of several possible implementations of the power set (the set of all subsets) algorithm in Python. Some are recursive, some are iterative, some of them don't use
reduce
. Plenty of options to choose from!函数
reduce()
始终可以被for
循环替换。下面是reduce()
的 Python 实现:(与 Python 内置版本的
reduce()
相比,该版本不允许传入None< /code> 作为
start
参数。)将此代码与传递给
reduce()
的参数进行特殊封装可以得到The function
reduce()
can always be reaplaced by afor
loop. Here's a Python implementation ofreduce()
:(In contrast to Python's built-in version of
reduce()
, this version does not allow to pass inNone
asstart
parameter.)Special-casing this code with the parameters you passed to
reduce()
gives