Python 如何实现受限组合迭代器?

Python 如何实现受限组合迭代器?,python,python-2.7,math,python-3.x,Python,Python 2.7,Math,Python 3.x,我想要与以下代码等价的东西。 下面的代码生成扑克可能的手牌模式 from itertools import combinations m = 13 n = 4 x = range(m) * n y = 5 pattern = set() for i in combinations(x, y): pattern.add(tuple(sorted(i))) 我尝试使用itertools.compositions\u替换。毫不奇怪,有像0、0、0、0或1、1、1、1、1这样的组合。但是一张牌

我想要与以下代码等价的东西。 下面的代码生成扑克可能的手牌模式

from itertools import combinations
m = 13
n = 4
x = range(m) * n
y = 5
pattern = set()
for i in combinations(x, y):
    pattern.add(tuple(sorted(i)))
我尝试使用itertools.compositions\u替换。毫不奇怪,有像0、0、0、0或1、1、1、1、1这样的组合。但是一张牌里没有5个皇后和5个国王。所以我不想拿同样的东西。如何实现受限组合迭代器

from itertools import combinations_with_replacement
m = 13
n = 4
x = range(m)
y = 5
pattern = []
for i in combinations_with_replacement(x, y):
    pattern.append(i)
我想像下面的代码

伪代码:

另外,由于我是英语学习者,请修改我的语法错误。

阅读文档后:

我发现您的目标的内置解决方案不存在

因此,如果你想这样做,我认为两种解决方案可能是合适的:

[1] 。让你所有的卡片都与众不同:

from itertools import combinations
m = 13
n = 4
x = range(m * n)
y = 5
pattern = set()
# combinations from range(0, 52)
for i in combinations(x, y):
    # so p/n maps to range(0, 13)
    pattern.add((p / n for p in sorted(i)))
[2] 。排除所有无效结果:

from itertools import combinations
m = 13
n = 4
x = range(m) * n
y = 5
pattern = set()
for i in combinations(x, y):
    if min(i) == max(i):
        continue
    pattern.add(tuple(sorted(i)))
您可以这样做:

import itertools
# each card is a pair (value,  color)
cards = [ (value, color) for value in xrange(13) for color in xrange(4) ] 
# all 5 cards combinations within 52 cards
for hand in itertools.combinations( cards, 5 ) :
  print hand

max=n是什么意思?@fish\u ball意思是你不能画5个皇后或5个国王或其他。但是你最多可以画4个皇后或4个国王或其他。keimina你当前的代码不能画同一张牌的5张。为什么你要更换,这不是扑克手的处理方式。你能更清楚地说明你目前的代码有什么问题吗?@jornsharpe:是的,你是对的。我更新了我的问题。我只是不想使用set或if,因为我想快速计算模式。@keimina为什么你认为set不快?您是否有特定的性能问题?你分析过它吗?
import itertools
# each card is a pair (value,  color)
cards = [ (value, color) for value in xrange(13) for color in xrange(4) ] 
# all 5 cards combinations within 52 cards
for hand in itertools.combinations( cards, 5 ) :
  print hand