开发者

Convert args to flat list?

开发者 https://www.devze.com 2022-12-24 19:05 出处:网络
I know this is very similar to a few other questions, but I can\'t quite get this function to work correctly.

I know this is very similar to a few other questions, but I can't quite get this function to work correctly.

def flatten(*args):
    return list(item for iterable in args for item in iterable)

The output I'm looking for is:

flatten(1) -> [1]
flatten(1,[2]) -> [1, 2]
flatten([1,[2]]) -> [1, 2]

The current function, which I took from another SO answer, doesn't seem to produce correct results at all:

>>> flatten([1,[2]])
[1, [2]]开发者_开发百科


For a quick solution, just take your second function and make it recursive.

def flatten(*args):
    output = []
    for arg in args:
        if hasattr(arg, '__iter__'):
            output.extend(flatten(*arg))
        else:
            output.append(arg)
    return output


If you want to flatten arbitrarily nested lists you need a recursive function:

def flatten(ls):
  if isinstance(ls, list):
     return [fa for a in ls for fa in flatten(a)]
  else:
     return [ls]

(If you expect to flatten big structures this could be made more efficient by using generators instead of returning lists.)

This function can also be reused to create a function that takes multiple parameters:

def pflatten(*ls):
   return flatten(list(ls))


Checking __iter__ presence can be quite strange when flattening dictionary:

>>> def flatten(*args):
...     output = []
...     for arg in args:
...         if hasattr(arg, '__iter__'):
...             output.extend(flatten(*arg))
...         else:
...             output.append(arg)
...     return output
...
>>> adict = {1:2, 3:4, 5:6}
>>> blist = ['a', 'b', 'c']
>>> raw = [adict, blist]
>>> flatten(raw)
[1, 3, 5, 'a', 'b', 'c']

I think flatten should work for lists and tuples only:

import types

def flatten(*args):
    output = []
    for arg in args:
        if isinstance(arg, (types.ListType, types.TupleType)):
            output.extend(flatten(*list(arg)))
        else:
            output.append(arg)
    return output

adict = {1:2, 3:4, 5:6}
blist = ['a', 'b', 'c']
raw = [adict, blist]
print flatten(raw)


Solved it...

def flatlist(*args):
    lst = []
    for a in args:
        if hasattr(a, '__iter__'): lst.extend(flatlist(*a))
        else: lst.append(a)
    return lst
0

精彩评论

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