﻿ 寻求优雅的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]
``````

``````>>> 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