如何获得集合的所有子集? (电源集)

编程入门 行业动态 更新时间:2024-10-28 02:21:16
本文介绍了如何获得集合的所有子集? (电源集)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

提供一套

{0, 1, 2, 3}

如何生成子集:

[set(), {0}, {1}, {2}, {3}, {0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}, {0, 1, 2}, {0, 1, 3}, {0, 2, 3}, {1, 2, 3}, {0, 1, 2, 3}]

推荐答案

Python itertools页面具有与此完全相同的powerset配方:

The Python itertools page has exactly a powerset recipe for this:

from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

输出:

>>> list(powerset("abcd")) [(), ('a',), ('b',), ('c',), ('d',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd')]

如果您一开始不喜欢该空元组,则可以将range语句更改为range(1, len(s)+1)以避免长度为0的组合.

If you don't like that empty tuple at the beginning, you can just change the range statement to range(1, len(s)+1) to avoid a 0-length combination.

更多推荐

如何获得集合的所有子集? (电源集)

本文发布于:2023-11-09 13:45:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572517.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子集   如何获得   电源

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!