我有一个输入

A = [2,0,1,3,2,2,0,1,1,2,0].

接下来我通过
A = list(Set(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库。但没办法解决。

最佳答案

>>> 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

10-04 19:15