2014-02-07 62 views
7

我如何轉換:如何在python中拼合嵌套列表?

THIS = \ 
['logging', 
['logging', 'loggers', 
    ['logging', 'loggers', 'MYAPP', 
    ['logging', 'loggers', 'MYAPP', '-handlers'], 
    ['logging', 'loggers', 'MYAPP', 'propagate'] 
    ] 
], 
['logging', 'version'] 
] 

到:

THAT = [ 
    ['logging'], 
    ['logging', 'version'], 
    ['logging', 'loggers'], 
    ['logging', 'loggers', 'MYAPP'], 
    ['logging', 'loggers', 'MYAPP', '-handlers'], 
    ['logging', 'loggers', 'MYAPP', 'propagate'] 
] 
在python

(不需要進行排序,只是變平)?

我試過很多東西,但找不到如何解決這個問題。

+1

http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-列表中的列表中的蟒蛇 – dstromberg

+1

請參閱[這個問題](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python),尤其是[這個答案](http:///stackoverflow.com/a/406822/1535629)。 – senshin

+0

另請參閱:http://stackoverflow.com/questions/11377208/recursive-generator-for-flattening-nested-lists?rq=1 – wheaties

回答

2

解決與遞歸發電機

def flatten(items): 
    non_list_items = [] 

    for item in items: 
     if isinstance(item, list): 
      for inner_item in flatten(item): 
       yield inner_item 
     else: 
      non_list_items.append(item) 

    yield non_list_items 

測試對您輸入:

from pprint import pprint 

>>> pprint(sorted(flatten(THIS))) 
[['logging'], 
['logging', 'loggers'], 
['logging', 'loggers', 'MYAPP'], 
['logging', 'loggers', 'MYAPP', '-handlers'], 
['logging', 'loggers', 'MYAPP', 'propagate'], 
['logging', 'version']] 
+0

謝謝我一直在努力爭取這個年齡 – jbrown

1

這是一個遞歸函數真正的亮點:

def flatten(myList): 
    def inner(current, acc): 
    items = [] 
    for x in myList: 
     if isinstance(x, list): 
     acc.extend(inner(x, [])) 
     else: 
     items.append(x) 
    acc.extend(items) 
    return acc 

    return inner(myList, []) 

我認爲應該做的伎倆。