Get sorted combinations

£可爱£侵袭症+ 提交于 2019-12-22 07:44:57

问题


I have a input like

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

Following I remove all the duplicates by

A = list(Set(A))

A is now [0,1,2,3]. Now I want all the pair combinations that I can make with this list, however they do not need to be unique... thus [0,3] equals [3,0] and [2,3] equals [3,2]. In this example it should return

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

How do I achieve this? I looked in the iteratools lib. But couldn't come up with a solution.


回答1:


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


来源:https://stackoverflow.com/questions/5560479/get-sorted-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!