2013-06-11 48 views
0

在Python中,是否有更好的方式從嵌套for循環或列表推導中獲得k元素集合中的n個元素組合?例如,從集合[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)]。有沒有比製作組合(Python)

更好的 ​​

?如果列表中的元素是集合,元組或列表,那沒關係;我只是覺得應該有一個更簡單的方法來做到這一點。

+0

谷歌自己的問題相關的標題,然後點擊第一個鏈接。 – Blender

回答

3

itertools模塊有很多功能非常強大的工具,可以在這種情況下使用。在這種情況下,你想要itertools.combinations。其他一些你可能會覺得有用的是itertools.combinations_with_replacementitertools.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)] 
3

您可以使用itertools.combinations

>>> from itertools import combinations 
>>> nums = [1,2,3,4,5,6] 
>>> list(combinations(nums, 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)] 
1

您可以使用itertools模塊裏

import itertools 
alphabet = ['1','2','3','4','5','6'] 
combos = list(itertools.combinations(alphabet, 2)) 
print combos