如何在python中对所有组合进行排序?

Rib*_*ibz 2 python combinations

我有K=2N=3我生成所有组合如下:

list(itertools.product(range(1, N+1), repeat=K))
Run Code Online (Sandbox Code Playgroud)

我明白了

[(1, 1), 
 (1, 2),
 (1, 3), 
 (2, 1), 
 (2, 2), 
 (2, 3), 
 (3, 1), 
 (3, 2), 
 (3, 3)]
Run Code Online (Sandbox Code Playgroud)

我需要对这些组合进行排序才能获得

[(1, 1), 
 (2, 2),
 (3, 3),
 (1, 2),
 (1, 3), 
 (2, 1), 
 (2, 3), 
 (3, 1), 
 (3, 2)]
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做一般KN

就像有N垃圾箱和K物品一样,我想把所有可能的物品分配到垃圾箱,但从开始

  • 分配给bin 1,bin 2等的所有项目.
  • 分配给bin 1的K-1项目和bin 2中的一个项目等.
  • ...

因此在该示例中(1, 1)意味着所有项目都在箱子1中,(2, 2)意味着所有物品都在箱子2中,等等(1, 2)意味着物品1在箱子1中而物品2在箱子2中,等等.

wim*_*wim 6

几乎已经生成了你想要的,所以你可以利用python的排序稳定:

>>> L = list(itertools.product(range(1, N+1), repeat=K))
>>> L.sort(key=lambda t: len(set(t)))
>>> L
[(1, 1), (2, 2), (3, 3), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
Run Code Online (Sandbox Code Playgroud)

这只是将具有最相等值的元组推向前方.它应该推广到与您描述的方式一致的更高维度.