Python 中的多范围产品

发布于 2024-08-30 01:02:00 字数 747 浏览 1 评论 0原文

有没有更好的方法来做到这一点:

perms = product(range(1,7),range(1,7),range(1,7))

以便我可以选择使用多少个范围? 我希望它与此等效,但可扩展。

def dice(num)
    if num == 1:
        perms = ((i,) for i in range(1,7))
    elif num == 2:
        perms = product(range(1,7),range(1,7))
    elif num == 3:
        perms = product(range(1,7),range(1,7),range(1,7))
    #... and so on

但我知道必须有更好的方法。 我用它来计算骰子的结果。 实际代码

def dice(selection= lambda d: d[2]):   
    perms = itertools.product(range(1,7),range(1,7),range(1,7))      
    return collections.Counter(((selection(sorted(i)) for i in perms)))

我可以使用各种选择器调用它的 ,例如 sum(d[0:2]) 表示最低 2 个骰子的总和或 d[1] > 得到中间的骰子。

Is there a better way to do this:

perms = product(range(1,7),range(1,7),range(1,7))

so that I can choose how many ranges I use?
I want it to be equivalent to this, but scalable.

def dice(num)
    if num == 1:
        perms = ((i,) for i in range(1,7))
    elif num == 2:
        perms = product(range(1,7),range(1,7))
    elif num == 3:
        perms = product(range(1,7),range(1,7),range(1,7))
    #... and so on

but I know there has to be a better way.
I'm using it for counting dice outcomes.
The actual code

def dice(selection= lambda d: d[2]):   
    perms = itertools.product(range(1,7),range(1,7),range(1,7))      
    return collections.Counter(((selection(sorted(i)) for i in perms)))

where I can call it with a variety of selectors, like sum(d[0:2]) for the sum of the lowest 2 dice or d[1] to get the middle dice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

望笑 2024-09-06 01:02:00

是的。使用 repeat 关键字参数:

perms = product(range(1, 7), repeat=3)

请参阅文档 了解更多。

Yes. Use the repeat keyword argument:

perms = product(range(1, 7), repeat=3)

See the docs for more.

反差帅 2024-09-06 01:02:00

我认为

perms = itertools.product(*([xrange(1,7)]*num))

应该适合你。

I think

perms = itertools.product(*([xrange(1,7)]*num))

should work for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文