[英]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.