查找任意国家的列表的所有组合

2024-04-19 13:31:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来生成给定列表中的所有项组合,并输出给定的计数。输入将是列表和每个返回组合中的项目数。例如:

list = [a, b, c, d]
number of items in output: 2

退货:

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

输出项数为3的相同列表

退货:

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

注意(a,b)=(b,a)等

谢谢!你知道吗


Tags: of方法innumber列表outputitemslist
2条回答

itertools有一个permutations函数和combinations。你知道吗

你想要^{}

>>> list(itertools.combinations(['a', 'b', 'c', 'd'], 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> list(itertools.combinations(['a', 'b', 'c', 'd'], 3))
[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]

相关问题 更多 >