[英]Understanding Specific Python List Comprehension
鉴于骰子的数量和面数,我正在尝试使用此代码来产生掷骰子的所有可能结果。 这段代码有效(但我不太明白列表理解是如何工作的。
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
我对这个问题(以及一般的列表推导式)的第一直觉是使用递归。 尽管您要求使用 LOOPS,但这是非常具有挑战性的。
这就是我想出的;
def dice_rollsj(dice, sides):
result = [[]]
for num_dice in range(dice):
temp_result = []
for possible_new_values in range(1, sides+1):
for existing_values in result:
new_tuple = existing_values + [possible_new_values]
temp_result.append(new_tuple)
result = temp_result
我认为您会得到相同的正确答案,但数字的顺序不同。 这可能是由于将值附加到列表的方式造成的。 我不知道......如果这有帮助,请告诉我。
我试图添加尽可能多的行,因为目标是扩展和理解理解。
您正在重新定义for y in pool
循环中for y in pool
每次迭代的结果。 我相信你想要的是追加结果:
result = []
for x in result:
for y in pool:
result.append(x + [y])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.