2016-09-08 35 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