1

Possible Duplicate:
Flatten (an irregular) list of lists in Python

I wanted a solution to list/print all the items in a nested list (with arbitrary nesting level). Here is what I came up with:

items = []
def getitems(mylist):
    for item in mylist:
        if type(item) is list:
            getitems(item)
        else:
            items.append(item)
    return items

Sample output:

foo=['foo','bar',['foo','bar','baz'],'spam',['ham','eggs','salami']]

In [8]: getitems(foo)
Out[8]: 
['foo',
 'bar',
 'foo',
 'bar',
 'foo',
 'bar',
 'baz',
 'spam',
 'ham',
 'eggs',
 'salami']

Is this a good solution? Or is there a better approach?

4

1 回答 1

0

这可能有点迂腐,但您可以将累加器列表作为可选参数传递。这样一来,您就没有任何全局变量,并且可以避免在两次调用该函数并在第一次调用后忘记清除它时可能出现的问题:

def getitems(mylist, acc = None):
    if acc is None: acc = []
    for item in mylist:
        if type(item) is list:
            getitems(item, acc)
        else:
            acc.append(item)
    return acc
于 2012-08-09T11:39:54.380 回答