簡體   English   中英

遞歸嵌套列表

[英]Recursive Nested Lists

我無法解決遞歸嵌套列表中的問題。 問題; 需要定義一個過程來訪問嵌套列表到任意深度。 它需要一個嵌套列表和一個索引,然后在該索引處返回列表的一部分。 從這個給定的函數中,遞歸地找到給定索引處的值。

例如

好吧,這是一個更好的視覺表示。 要從中選擇元素9,我們需要執行nested [3] [1]之類的操作

nested = \
    [[[1, 2],
      3],
     [4,
      [5, 6]],
     7,
     [8, 9, 10]]

recursive_func(nested_list, [3,1]) #recursive function definition, the second argument is the index at which the data needs to be retrieved.  
>>> 9 #so given the function an index of [3,1] would return 9

為我指明正確方向的任何幫助將不勝感激

這可能會幫到您,但是我仍然不是100%確定您要尋找的東西...

>>> def findItem(nested, pos):
    if pos[0] == 1:
        return nested[pos[1]-1]
    else:
        nextLevelDown = []
        for item in nested:
            if type(item) == type([]):
                nextLevelDown = nextLevelDown + item
        return findItem(nextLevelDown, [pos[0]-1, pos[1]])

>>> findItem([[[1, 2], 3], 4], [3, 1])
1
>>> findItem([[[1, 2], [3]], 4], [3, 3])
3
>>> findItem([[[1, 2], [3]], 4], [2, 2])
[3]

更新:經過反復的反復,我終於明白了這個問題,它比原來看起來要簡單得多,您需要做的是:

>>> def recursiveRef(nested, idxList):
    if len(idxList) > 1:
        return recursiveRef(nested[idxList[0]], idxList[1:])
    return nested[idxList[0]] 

>>> recursiveRef([[[1, 2], 3], [4, [5, 6]], 7, [8, 9, 10]], [3, 1])
9

如果我正確理解這一點,則只想將嵌套列表變成非嵌套列表即可? 然后檢查索引? 如果是這樣,那么您可以嘗試這樣的事情(我目前沒有python,因此將其視為偽代碼):

def unwrap_list(list, result):
   if type(list) == type([]):
      for value in list:
         unwrap_list(value, result)
   else:
      result.append(list)

確保在調用此函數之前定義變量unwrap_list(list, unwrapped) unwrapped = [] ,並使用unwrap_list(list, unwrapped) 結果將存儲在unwrapped變量中。

暫無
暫無

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

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