开发者

Flattening mixed lists in Python (containing iterables and noniterables) [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Flatten (an irregular) list of lists in Python

How would I go about flattening a list in Python that contains both iterables and noniterables, such as [1, [2, 3, 4], 5, [6]]? The result should be [1,2,3,4,5,6], and lists of lists of lists (etc.) are certain never to occur.

I have tried using itertools.chain, etc., but t开发者_如何学JAVAhey seem only to work on lists of lists. Help!


So you want to flatten only 1 or 2 levels, not recursively to further depts; and only within lists, not other iterables such as strings, tuples, arrays... did I get your specs right? OK, if so, then...:

def flat2gen(alist):
  for item in alist:
    if isinstance(item, list):
      for subitem in item: yield subitem
    else:
      yield item

If you want a list result, list(flat2gen(mylist)) will produce it.

Hope this is trivially easy for you to adapt if your actual specs are minutely different!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜