如何以所有可能的方式将列表拆分成对 [英] How to split a list into pairs in all possible ways

查看:44
本文介绍了如何以所有可能的方式将列表拆分成对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表(为简单起见,说 6 个元素)

L = [0, 1, 2, 3, 4, 5]

并且我想以所有可能的方式将其分成两部分.我展示了一些配置:

[(0, 1), (2, 3), (4, 5)][(0, 1), (2, 4), (3, 5)][(0, 1), (2, 5), (3, 4)]

等等.这里 (a, b) = (b, a) 并且对的顺序并不重要,即

[(0, 1), (2, 3), (4, 5)] = [(0, 1), (4, 5), (2, 3)]

此类配置的总数为1*3*5*...*(N-1),其中N 是我的列表长度.>

如何用 Python 编写一个生成器,为我提供任意 N 的所有可能配置?

解决方案

看看 itertools.combinations.

matt@stanley:~$ pythonPython 2.6.5(r265:79063,2010 年 4 月 16 日,13:57:41)[GCC 4.4.3] 在 linux2输入帮助"、版权"、信用"或许可"以获取更多信息.>>>导入迭代工具>>>列表(itertools.combinations(范围(6),2))[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

I have a list (say 6 elements for simplicity)

L = [0, 1, 2, 3, 4, 5]

and I want to chunk it into pairs in ALL possible ways. I show some configurations:

[(0, 1), (2, 3), (4, 5)]
[(0, 1), (2, 4), (3, 5)]
[(0, 1), (2, 5), (3, 4)]

and so on. Here (a, b) = (b, a) and the order of pairs is not important i.e.

[(0, 1), (2, 3), (4, 5)] = [(0, 1), (4, 5), (2, 3)]

The total number of such configurations is 1*3*5*...*(N-1) where N is the length of my list.

How can I write a generator in Python that gives me all possible configurations for an arbitrary N?

解决方案

Take a look at itertools.combinations.

matt@stanley:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> list(itertools.combinations(range(6), 2))
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

这篇关于如何以所有可能的方式将列表拆分成对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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