2011-04-06 4 views
4

A = [2,0132201120]과 같은 입력이 있습니다.정렬 된 조합 가져 오기

제가 A =리스트 (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 lib를 들여다 보았다. 그러나 해결책을 찾지 못했습니다.

답변

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. 방금 조합 함수가 [2,0132201120]의 모든 조합을 만드는 원인이 된 A = list (Set (A))를 지정하는 것을 잊었습니다. – WGL

+0

@WGL, 나는 방금 질문 제목에서 "정렬"을 발견했습니다. 'list (set (A))'대신'sorted (set (A))'를 사용해야합니다. –

관련 문제