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

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

问题描述

我有一个包含 15 个数字的列表,我需要编写一些代码来生成这些数字的所有 32,768 个组合.

我发现 一些代码(通过谷歌搜索)显然符合我的要求,但我发现代码相当不透明,并且对使用它持谨慎态度.另外,我觉得必须有一个更优雅的解决方案.

我唯一想到的就是循环遍历十进制整数 1–32768 并将它们转换为二进制,然后使用二进制表示作为过滤器来挑选合适的数字.

有人知道更好的方法吗?使用 map(),也许?

解决方案

看看 itertools.combinations:

<块引用>

itertools.combinations(iterable, r)

返回r个元素的长度子序列来自输入可迭代.

组合按字典排序顺序发出.所以,如果输入迭代已排序,组合元组将在排序顺序.

自 2.6 起,包含电池!

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.

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?

解决方案

Have a look at itertools.combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Since 2.6, batteries are included!

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

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