寻求优雅的Python骰子迭代 - 代码日志

寻求优雅的Python骰子迭代

有没有一个优雅的方式来迭代可能的骰子卷与多达五个骰子?

我想替换这个黑客Python:

self.rolls[0] = [str(a) for a in range(1,7)]
self.rolls[1] = [''.join([str(a), str(b)])
                 for a in range(1, 7)
                 for b in range(1, 7)
                 if a <= b]
self.rolls[2] = [''.join([str(a), str(b), str(c)])
                 for a in range(1, 7)
                 for b in range(1, 7)
                 for c in range(1, 7)
                 if a <= b <= c]
self.rolls[3] = [''.join([str(a), str(b), str(c), str(d)])
                 for a in range(1, 7)
                 for b in range(1, 7)
                 for c in range(1, 7)
                 for d in range(1, 7)
                 if a <= b <= c <= d]
self.rolls[4] = [''.join([str(a), str(b), str(c), str(d), str(e)])
                 for a in range(1, 7)
                 for b in range(1, 7)
                 for c in range(1, 7)
                 for d in range(1, 7)
                 for e in range(1, 7)
                 if a <= b <= c <= d <= e]
您可以使用itertoolscombinations_with_replacement

例如3个4面骰子(只是因为输出不是太大):

>>> from itertools import combinations_with_replacement

>>> dice = 3
>>> faces = 4
>>> list(combinations_with_replacement(range(1, faces+1), dice))
[(1, 1, 1),
 (1, 1, 2),
 (1, 1, 3),
 (1, 1, 4),
 (1, 2, 2),
 (1, 2, 3),
 (1, 2, 4),
 (1, 3, 3),
 (1, 3, 4),
 (1, 4, 4),
 (2, 2, 2),
 (2, 2, 3),
 (2, 2, 4),
 (2, 3, 3),
 (2, 3, 4),
 (2, 4, 4),
 (3, 3, 3),
 (3, 3, 4),
 (3, 4, 4),
 (4, 4, 4)]
http://stackoverflow.com/questions/34876784/seeking-elegant-python-dice-iteration

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:寻求优雅的Python骰子迭代