2024-04-19 13:31:08 发布
网友
我正在寻找一种方法来生成给定列表中的所有项组合,并输出给定的计数。输入将是列表和每个返回组合中的项目数。例如:
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)等
谢谢!你知道吗
itertools有一个permutations函数和combinations。你知道吗
itertools
你想要^{}:
>>> 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')]
itertools
有一个permutations函数和combinations。你知道吗你想要^{} :
相关问题 更多 >
编程相关推荐