[英]Recursive function calls in python in list comprehension gives different result than assigning the result of the call to a variable first
為什么不這樣:
def subsets(x):
if not x:
return [[]]
else:
return [x + y for x in [[], [x[0]]] for y in subsets(x[1:])]
print subsets(['a', 'b'])
產生與此相同的輸出:
def subsets(x):
if not x:
return [[]]
else:
z = subsets(x[1:])
return [x + y for x in [[], [x[0]]] for y in z]
print subsets(['a', 'b'])
問題是您將名稱x
用於兩種不同的事物。 當您將x
作為變量引入列表理解中時,它會隱藏x
中定義的x
。 結果,列表理解中的最后一個x
並未引用您希望的x
。
將x
之一重命名為其他名稱可解決此問題:
def subsets(original_x):
if not original_x:
return [[]]
else:
return [x + y for x in [[], [original_x[0]]]
for y in subsets(original_x[1:])]
我還建議您嘗試為變量找到更多的描述性名稱。 這將減少意外重用名稱的可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.