关于python:如何使用列表推导在循环内进行列表展平?

How to do List flattening inside the loop with list comprehension?

这里我有一个字典列表,我的目标是遍历列表,每当有两个或更多的列表可用时,我希望合并它们并追加到一个输出列表中,每当只有一个列表时,需要将其存储为它的形式。

1
2
3
4
5
6
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]进行列表扁平化。

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

预期输出:

1
2
3
4
5
6
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'}]
        ]

对于那些需要扁平化的元素,可以将条件列表理解与itertools.chain一起使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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'}]]


试试这个,

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

具有列表理解功能的单行代码,

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

替代方法,

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

结果

1
2
3
4
5
6
7
8
9
10
[[{'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'}]]


遍历列表并检查每个项是否是列表列表。如果是这样,把它压平。

1
2
3
4
5
6
7
8
9
10
11
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