2011-04-06 69 views
4

我有一个输入,如 A = [2,0,1,3,2,2,0,1,1,2,0]。获取排序组合

继我通过 A =列表中删除所有重复的(设置(A))

A现在[0,1,2,3]。现在我想要我可以用这个列表创建的所有对组合,但它们不需要是唯一的...因此[0,3]等于[3,0]和[2,3]等于[3,2] 。在这个例子中它应该返回

[[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]]

我该如何做到这一点?我查看了iteratools库。但无法提出解决方案。

回答

11
>>> A = [2,0,1,3,2,2,0,1,1,2,0] 
>>> A = sorted(set(A)) # list(set(A)) is not usually in order 
>>> from itertools import combinations 
>>> list(combinations(A, 2)) 
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] 

>>> map(list, combinations(A, 2)) 
[[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]] 

>>> help(combinations) 
Help on class combinations in module itertools: 

class combinations(__builtin__.object) 
| combinations(iterable, r) --> combinations object 
| 
| Return successive r-length combinations of elements in the iterable. 
| 
| combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3) 
| 
| Methods defined here: 
| 
| __getattribute__(...) 
|  x.__getattribute__('name') <==> x.name 
| 
| __iter__(...) 
|  x.__iter__() <==> iter(x) 
| 
| next(...) 
|  x.next() -> the next value, or raise StopIteration 
| 
| ---------------------------------------------------------------------- 
| Data and other attributes defined here: 
| 
| __new__ = <built-in method __new__ of type object> 
|  T.__new__(S, ...) -> a new object with type S, a subtype of T 
+0

谢谢...我只是noticted该组合确实是正常工作。我忘了分配A = list(Set(A)),它导致组合函数创建[2,0,1,3,2,2,0,1,1,2,0]的所有组合。 – WGL 2011-04-06 01:34:28

+0

@WGL,我只是注意到在问题标题中“排序”。你应该使用'sorted(set(A))'而不是'list(set(A))' – 2011-04-06 02:09:50