2015-06-16 66 views
2

如果我有兩個字符串的元組列表的列表的列表。我想壓平到元組的非嵌套列表,我可以這樣做:有沒有辦法避免這麼多的鏈表(chain(* list_of_list))?

>>> from itertools import chain 
>>> lst_of_lst_of_lst_of_tuples = [ [[('ab', 'cd'), ('ef', 'gh')], [('ij', 'kl'), ('mn', 'op')]], [[('qr', 'st'), ('uv', 'w')], [('x', 'y'), ('z', 'foobar')]] ] 
>>> lllt = lst_of_lst_of_lst_of_tuples 
>>> list(chain(*list(chain(*lllt)))) 
[('ab', 'cd'), ('ef', 'gh'), ('ij', 'kl'), ('mn', 'op'), ('qr', 'st'), ('uv', 'w'), ('x', 'y'), ('z', 'foobar')] 

但有拆包元組的非嵌套列表withou嵌套list(chain(*lst_of_lst))的另一種方式?

回答

2

你可以繼續拆封,直到你打的元組:

def unpack_until(data, type_): 
    for entry in data: 
     if isinstance(entry, type_): 
      yield entry 
     else: 
      yield from unpack_until(entry, type_) 

然後:

>>> list(unpack_until(lllt, tuple)) 
[('ab', 'cd'), 
('ef', 'gh'), 
('ij', 'kl'), 
('mn', 'op'), 
('qr', 'st'), 
('uv', 'w'), 
('x', 'y'), 
('z', 'foobar')] 
4

你不需要解壓一個迭代器之前調用list

list(chain(*chain(*lllt))) 

這可能是最好使用chain.from_iterable而不拆包,迭代器的工作具體化他們到元組*代替:

flatten = chain.from_iterable 
list(flatten(flatten(lllt))) 
相關問題