获取排序的组合 [英] Get sorted combinations
本文介绍了获取排序的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入,例如
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]
。在此示例中,它应返回
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]]
我如何实现这个?我查看了 iteratools
库。
How do I achieve this? I looked in the iteratools
lib. But couldn't come up with a solution.
推荐答案
>>> 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
这篇关于获取排序的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文