如何打印列表的所有独特组合?

发布于 2025-01-28 23:59:21 字数 163 浏览 1 评论 0原文

list_a = [1, 2, 3]

我想打印列表中的所有唯一组合,如此

[ [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3] ]

注:不使用任何模块

list_a = [1, 2, 3]

I want to print all the unique combinations from the list like this

[ [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3] ]

Note: Without using any module

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼趣 2025-02-04 23:59:21

您需要 powerset refipe =“ https://docs.python.org/3/library/itertools.html” rel =“ nofollow noreferrer”> itertools

from itertools import combinations, chain
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(1, len(s)+1))

list_a = [1, 2, 3]

out = list(map(list, powerset(list_a)))

output:[[1],,,,,,,,,,,地[2],[3],[1,2],[1,3],[2,3],[1,2,3]]

如果您不想使用itertools使用列表综合或功能,您可以很容易地轻松地重新进来组合链条 。

You need a variant of the powerset recipe from itertools:

from itertools import combinations, chain
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(1, len(s)+1))

list_a = [1, 2, 3]

out = list(map(list, powerset(list_a)))

output: [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

If you don't want to use itertools you can quite easily reimplement combinations and chain using list comprehensions or functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文