2012-12-13 2 views
2

계층 적 사전으로 변환해야하는 중첩 목록이 있습니다. 그러나 나는 깨끗한 비단뱀 방식으로 그것을 달성하는 방법을 조금 혼란스러워합니다. 여기에 다소 이상한 샘플 코드가 있습니다. 그것을 향상시키는 방법?계층 적 dict에 중첩 목록

from itertools import tee,izip 
import json 

L=[(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)] 

def pairs(iterable): 
    a,b = tee(iterable) 
    b.next() 
    return izip(a,b) 

def innerfunc(pairs,d): 
    try: 
     pair   = pairs.next() 
     item, nextitem = pair   
    except StopIteration:  
     return 
    if item in d:   
     innerfunc(pairs,d[item]) 
    else:   
     d[item]= {} 
     {nextitem : innerfunc(pairs,d[item])} 


def outerfunc(matrix): 
    result_dict={} 
    for row in matrix:   
     iter_pairs = pairs(row+(0,)) 
     innerfunc(iter_pairs,result_dict) 
    return result_dict 

print json.dumps(outerfunc(L), sort_keys=True, indent=4) 

출력 :

{ 
    "1": { 
     "2": { 
      "3": { 
       "4": { 
        "5": {} 
       } 
      }, 
      "7": {} 
     } 
    }, 
    "2": { 
     "3": { 
      "5": {} 
     } 
    }, 
    "3": { 
     "4": { 
      "5": { 
       "6": {} 
      } 
     } 
    } 
} 

답변

2

당신은 재귀를 사용하여 매우 간결하게이 작업을 수행 할 수 있습니다

def append_path(root, paths): 
    if paths: 
     child = root.setdefault(paths[0], {}) 
     append_path(child, paths[1:]) 

# Example usage 
root = {} 
for p in [(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)]: 
    append_path(root, p) 

# Print results 
import json 
print json.dumps(root, indent=4) 

출력 :

{ 
    "1": { 
     "2": { 
      "3": { 
       "4": { 
        "5": {} 
       } 
      }, 
      "7": {} 
     } 
    }, 
    "2": { 
     "3": { 
      "5": {} 
     } 
    }, 
    "3": { 
     "4": { 
      "5": { 
       "6": {} 
      } 
     } 
    } 
} 
+0

감사합니다. 이것은 훨씬 나아 보인다. – root

+0

@root를 환영합니다. –

+0

오, 당신이 접두사 일치를 위해 trie를 구현하는 데 이것을 사용한다고 가정하면 잠깐 뒤에 게시 한 스 니펫이 있습니다. https://gist.github.com/736416 –