开发者

Decompose list of lists into single list with non-iterable list elements

Ref: python decompose a list Flattening a shallow list in Python

While the above mentioned solutions are helpful, my problem is slightly different, and I was wondering if there is a pythonic way to solve it.

a = [['a-3','b-3'],'r',['j']]

What I woul开发者_如何学运维d like, is a clean way of making 'a' equal the following:

a = ['a-3','b-3','r','j']

I am stuck using python 2.4 so a pythonic solution that's 2.4 compatible would be great, but I would still find 2.7+ examples interesting as well.

The main problem is that there are non-iterable elements, otherwise the sum(lst,[]) works quite well, as does the chain method for 2.7+


Pythonic solution can mean many thing. With readability counts (PEP 20) in mind, this is my contribution to the thread:

def dec(input_, output_):
    if type(input_) is list:
        for subitem in input_:
            dec(subitem, output_)
    else:
        output_.append(input_)

Example:

input_ = [['a-3','b-3', ['x','hello', ['3','b']]],'r',['j']]
output_ = ['a-3', 'b-3', 'x', 'hello', '3', 'b', 'r', 'j']


How about:

itertools.chain.from_iterable(map(lambda i: i if type(i) == list else [i], a))

or, for readability:

def assure_is_list(a):
   return a if type(a) == list else [a]

itertools.chain.from_iterable(map(assure_is_list, a))


def flatten(L):
    if not L:
        return L
    elif isinstance(L[0], list):
        return flatten(L[0]) + flatten(L[1:])
    else:
        return [L[0]] + flatten(L[1:])

Hope this helps


Recursive flattening of any iterable types, except leaving strings alone (since you probably don't want to split those into characters):

def flatten(x):
  try:
    if isinstance(x, basestring): raise TypeError
    y = iter(x)
  except TypeError:
    yield x
    return
  for item in y:
    for subitem in flatten(item):
      yield subitem


Think that you can also use something like this:

data = [['a-3','b-3', ['x','hello', ['3','b']]],'r',['j']]

while not all(not isinstance(x, list) for x in data):
    for i in xrange(len(data)):
        value = data.pop(i)
        if isinstance(value, list):
            data.extend(value)    
        else:
            data.append(value)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜