如何获得列表元素的所有可能组合? [英] How to get all possible combinations of a list’s elements?

查看:85
本文介绍了如何获得列表元素的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含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!

这篇关于如何获得列表元素的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆