繁体   English   中英

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

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

这里我有字典列表,我的目标是迭代列表,每当有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]扁平化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'}]
        ]

您可以对itertools.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'}]]

尝试这个,

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'}]]

遍历列表并检查每个项目是否为列表列表。 如果这样平整它。


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM