我是靠谱客的博主 刻苦裙子,这篇文章主要介绍python扁平化界面,如何在python中扁平化列表列表,现在分享给大家,希望可以做个参考。

I've seen a couple answers on how to flatten lists of the form

[1,[1,2],[3]]

print list(itertools.chain(*[1,[1,2],[3]]))

but how do you flatten lists like this:

[[1],[[1,2],[3]]]

print list(itertools.chain(*[[1],[[1,2],[3]]]))

[1, [1, 2], [3]]

解决方案

I usually use this recipe:

import collections

def flatten(l):

for el in l:

if isinstance(el, collections.Iterable) and not isinstance(el, str):

for sub in flatten(el):

yield sub

else:

yield el

print(list(flatten([[1],[[1,2],[3]]])))

# [1, 1, 2, 3]

最后

以上就是刻苦裙子最近收集整理的关于python扁平化界面,如何在python中扁平化列表列表的全部内容,更多相关python扁平化界面内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部