python – 获取已排序的组合

我有一个输入

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

下面我删除所有重复项

A = list(Set(A))

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

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

我该如何实现这一目标?我查看了iteratools lib.但无法提出解决方案.

最佳答案
>>> A = [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),3),(1,(2,3)]

>>> map(list,combinations(A,2))
[[0,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,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__ = __new__ of type object>
 |      T.__new__(S,...) -> a new object with type S,a subtype of T

相关文章

我最近重新拾起了计算机视觉,借助Python的opencv还有face_r...
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Poolin...
记得大一学Python的时候,有一个题目是判断一个数是否是复数...
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic ...
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic v...
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic ...