生成 python 列表的所有类型的唯一可能组合

发布于 01-13 10:00 字数 627 浏览 7 评论 0原文

你好,我需要知道如何以如此有趣的方式获得列表的所有唯一可能组合:

例如:

myLIST=[70,90,100]

我想制作两个或一个数字的唯一组合.. IE;

final_list=[ { [100 , 70] , [90] } , { [100 , 90] , [70] }]

在这个例子中: 可能只有这两个子列表;

作为;如果我采取 [{ [70,100] , [90] }][{[90,100],[70]}] 子列表组合开始重复,

Note : for a list of 5 elements;i just need those combination lists which have either 3 elemnts or two elements

例如:myLIST=[10,20,30,40,50]

final_list=[{[10,30,50],[20,40]}] , {[10,50],[20,50,30]} 等等..

这里我只采用了大小为 2 或 3 的子列表

hello i need to know how can i get all the unique possible combinations of a list in such an interesting way:

eg:

myLIST=[70,90,100]

i want to make either two or a single digit unique combination..
i.e;

final_list=[ { [100 , 70] , [90] } , { [100 , 90] , [70] }]

here in this example:
there possible only these two sublists;

as; if i take [{ [70,100] , [90] }] or [{[90,100],[70]}]
the sublists combinations starts repeating

Note : for a list of 5 elements;i just need those combination lists which have either 3 elemnts or two elements

eg:myLIST=[10,20,30,40,50]

final_list=[{[10,30,50],[20,40]}] , {[10,50],[20,50,30]}
and so on..

here i have taken only the sublists of size 2 or 3

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

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

发布评论

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

评论(1

晚风撩人2025-01-20 10:00:50

您可以使用 itertools(内置的 python 库)生成列表组合:

from itertools import combinations

sample_list = ['a', 'b', 'c', 'c']
list_combinations = list()
sample_set = set(sample_list)

for n in range(len(sample_set) + 1):
    list_combinations += list(combinations(sample_set, n))

print(list_combinations)

returns:

[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

您可以在此处找到有关 itertools 的更多信息:
https://datagy.io/python-combinations-of-a-list/< /a>

You can use itertools (a built-in python library) to generate combinations of lists:

from itertools import combinations

sample_list = ['a', 'b', 'c', 'c']
list_combinations = list()
sample_set = set(sample_list)

for n in range(len(sample_set) + 1):
    list_combinations += list(combinations(sample_set, n))

print(list_combinations)

returns:

[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

You can find more information about itertools here:
https://datagy.io/python-combinations-of-a-list/

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