簡體   English   中英

為什么我在 python 列表(遞歸)上收到列表錯誤?

[英]Why am I getting a list error on a python list (recursion)?

我正在嘗試在列表中創建自定義排列(主要是為了在 python 中處理遞歸)。 現在,當我運行代碼時出現此錯誤:

TypeError: 'NoneType' object is not iterable

在我添加列表復制之前,我得到了這個:

AttributeError: 'NoneType' object has no attribute 'append'

def findPermutations (size, max, curr_perm):
    if not curr_perm or len(curr_perm) < size:
        for i in range(1,max):
            new_arr = list(curr_perm)
            findPermutations(size, max, new_arr.append(i))
    else:
        return curr_perm


print(findPermutations(2,3,[]))

我希望返回一堆或排列。 我在這里做錯了什么?

您需要在調用遞歸函數之前附加項目列表。 以下是工作代碼,如果您有任何問題,請告訴我,我很樂意為您提供幫助。

def findPermutations (size, max, curr_perm):
    if not curr_perm or len(curr_perm) < size:
        for i in range(1,max):
            new_arr = list(curr_perm)
            new_arr.append(i)
            print(new_arr)
            findPermutations(size, max, new_arr)
    else:
        return curr_perm
findPermutations(2,3,[])
**Result:**
[1]
[1, 1]
[1, 2]
[2]
[2, 1]
[2, 2]

要解決您的代碼:

    new_arr.append(i)
    findPermutations(size, max, new_arr)

list.append()函數返回None

它不會返回新的更新列表。 它只是修改現有列表並返回None 因此None在隨后的遞歸調用中作為findPermutations()函數中的第三個參數傳遞。

@Wonka 的答案將代碼分成兩部分。 這允許首先更新new_arr列表,然后將其傳遞給函數。

在這里使用new_arr + [i]將是更好的選擇。 這將創建一個新列表,並將其傳遞給下一個遞歸函數調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM