如何获得列表元素的所有可能组合?
我有一个包含15个数字的列表,我需要编写一些代码来生成这些数字的所有32,768个组合。
I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
我发现一些代码(通过谷歌搜索)显然可以满足我的需求,但是我发现代码相当不透明并警惕使用它。另外,我觉得必须有一个更优雅的解决方案。
I've found some code (by Googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.
对我来说,唯一发生的就是循环十进制整数1–32768并将其转换转换为二进制,并使用二进制表示形式作为过滤器以选择适当的数字。
The only thing that occurs to me would be to just loop through the decimal integers 1–32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers.
有人知道更好的方法吗?
Does anyone know of a better way? Using map()
, maybe?
使用 map()
,也许? a href = http://docs.python.org/library/itertools.html#itertools.combinations rel = noreferrer> itertools.combinations :
Have a look at itertools.combinations:
itertools.combinations(iterable, r)
从
可迭代的输入中返回元素的r长度子序列。
Return r length subsequences of elements from the input iterable.
组合按字典顺序排序。因此,如果对
输入的iterable进行排序,则将按
排序的顺序生成
组合元组。
Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
从2.6开始,包括电池!
Since 2.6, batteries are included!