开发者

Join a list of lists together into one list in Python [duplicate]

开发者 https://www.devze.com 2023-01-03 07:49 出处:网络
This question already has answers here: Flatten an irregular (arbitrarily nested) list of lists (50 answers)
This question already has answers here: Flatten an irregular (arbitrarily nested) list of lists (50 answers) Closed 4 months ago.

I have a list which consists of many lists. Here is an example,

[
    [Obj, Obj, Obj, Obj],
    [Obj],
    [Obj],
    [
        [Obj,Obj],
        [Obj,Obj,Obj]
    ]
]

Is there a way to join all these items together as one list, so the output will be something like

[Obj开发者_如何学JAVA,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj]


Yes, here's one way to do it:

def flatten(lst):
    for elem in lst:
        if type(elem) in (tuple, list):
            for i in flatten(elem):
                yield i
        else:
            yield elem

Please note, this creates a generator, so if you need a list, wrap it in list():

flattenedList = list(flatten(nestedList))


Stolen from MonkeySage, here:

def iter_flatten(iterable):
  it = iter(iterable)
  for e in it:
    if isinstance(e, (list, tuple)):
      for f in iter_flatten(e):
        yield f
    else:
      yield e
0

精彩评论

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