2016-09-08 58 views
2

這裏我有詞典列表,我的目標是遍歷列表,每當有2個或更多列表可用,我想合併它們並追加在輸出列表中,並且每當只有一個列表時它需要存儲爲。如何做到列表理解的循環內列表展平?

data = [ 
      [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], 
      [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], 
      [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], 
      [{'font-weight': '3'},{'font-weight': '3'}] 
     ] 

我能做的列表展平特定元素data[0]

print([item for sublist in data[0] for item in sublist]) 
[{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}] 

預期輸出:

data = [ 
      [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}], 
      [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], 
      [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}] 
      [{'font-weight': '3'},{'font-weight': '3'}] 
     ] 

回答

5

你可以使用conditional list comprehensionitertools.chain這些元素這就需要扁平化:

In [54]: import itertools 

In [55]: [list(itertools.chain(*l)) if isinstance(l[0], list) else l for l in data] 
Out[55]: 
[[{'font-weight': '1'}, 
    {'font-weight': '1'}, 
    {'font-weight': '2'}, 
    {'font-weight': '2'}], 
[{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}], 
[{'font-weight': '1'}, 
    {'font-weight': '1'}, 
    {'font-weight': '2'}, 
    {'font-weight': '2'}], 
[{'font-weight': '3'}, {'font-weight': '3'}]] 
+0

完美!像老闆@Ami,謝謝 –

+0

我更喜歡這個答案Nice work, –

+0

@Rahul謝謝!我也喜歡你的回答。 –

3

試試這個,與列表理解

result = [] 
for item in data: 
    result.append([i for j in item for i in j]) 

單行代碼,

[[i for j in item for i in j] for item in data] 

替代方法,

import numpy as np 
[list(np.array(i).flat) for i in data] 

結果

[[{'font-weight': '1'}, 
    {'font-weight': '1'}, 
    {'font-weight': '2'}, 
    {'font-weight': '2'}], 
[{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}], 
[{'font-weight': '1'}, 
    {'font-weight': '1'}, 
    {'font-weight': '2'}, 
    {'font-weight': '2'}], 
[{'font-weight': '3'}, {'font-weight': '3'}]] 
0

遍歷列表並檢查每個項目是否是列表的列表。如果這樣平坦。


data = [ 
     [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], 
     [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}], 
     [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]], 
     [{'font-weight': '3'},{'font-weight': '3'}] 
     ] 
for n, each_item in enumerate(data): 
    if any(isinstance(el, list) for el in each_item): 
     data[n] = sum(each_item, []) 

print data