【发布时间】:2019-06-20 20:09:39
【问题描述】:
在给定骰子数量和面数的情况下,我正在尝试使用此代码产生掷骰子的所有可能结果。此代码有效(但我不太明白列表理解是如何工作的。
def dice_rolls(dice, sides):
"""
Equivalent to list(itertools.product(range(1,7), repeat=n)) except
for returning a list of lists instead of a list of tuples.
"""
result = [[]]
print([range(1, sides + 1)] * dice)
for pool in [range(1, sides + 1)] * dice:
result = [x + [y] for x in result for y in pool]
return result
因此,我正在尝试重写列表理解
result = [x + [y] for x in result for y in pool]
进入 FOR 循环以尝试了解其工作原理,但目前无法正确执行。当前失败代码:
for x in result:
for y in pool:
result = [x + [y]]
第二个问题:如果我想把它变成一个生成器(因为如果你有足够的骰子和边,这个函数是一个内存猪),我是否只是简单地产生列表中的每个项目,而不是抛出进入结果列表?
编辑:我想出了一种方法,在得到很好的响应后将列表理解分解为循环并想要捕获它:
def dice_rolls(dice, sides):
result = [[]]
for pool in [range(1, sides + 1)] * dice:
temp_result = []
for existing_values in result: # existing_value same as x in list comp.
for new_values in pool: # new_value same as y in list comp.
temp_result.append(existing_values + [new_values])
result = temp_result
return result
【问题讨论】:
-
如果你有足够的骰子和边数让这个函数成为内存问题,那么即使使用生成器,你也会遇到时间问题。您需要以一种不涉及枚举所有抛出结果的方式来解决您的潜在问题。
-
嗯,那就用
itertools.product吧? -
另外,是的,文档字符串甚至提到了
itertools.product。 -
我知道我可以只使用 itertools.product,这就是为什么我将它留在发布的代码中,但我正试图围绕这个特定的列表理解。
标签: python python-3.x generator list-comprehension