进行组合(Python) [英] Making Combinations (Python)

查看:50
本文介绍了进行组合(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,是否有比嵌套嵌套循环或列表理解更好的方法来从k元素集中获取n个元素的组合集?

In Python, is there a better way to get the set of combinations of n elements from a k-element set than nested for loops or list comprehensions?

例如,从集合[1,2,3,4,5,6]中说,我想获得[(1,2),(1,3 ),(1,4),(1,5),(1,6),(2,3),(2,4),(2,5),(2,6),(3,4), (3,5),(3,6),(4,5),(4,6),(5,6)]。是否比

For example, say from the set [1,2,3,4,5,6] I want to get [(1,2),(1,3),(1,4),(1,5),(1,6),(2,3),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6),(4,5),(4,6),(5,6)]. Is there a better of of making it than

nums=[1,2,3,4,5,6]
doubles=[]
for a in nums:
    for b in nums[a+1:]
        doubles.append((a,b))

?如果我们最终得到的列表的元素是集合,元组或列表,也可以;我只是觉得应该有一个更简单的方法来做到这一点。

? It's okay if the elements of the list we end up with are sets, tuples, or lists; I just feel there should be an easier way to do this.

推荐答案

itertools 模块具有很多非常强大的工具,可以在这种情况下使用。在这种情况下,您需要 itertools.combinations 。您可能会发现有用的其他一些工具是 itertools。 groups_with_replacement itertools.permutations

示例:

>>> import itertools
>>> list(itertools.combinations(range(1,7),2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
>>> list(itertools.combinations_with_replacement(range(1,7),2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6), (5, 5), (5, 6), (6, 6)]
>>> list(itertools.permutations(range(1,7),2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]

这篇关于进行组合(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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