Python如何拉平(flatten)嵌套列表(nested list)
来源:互联网 发布:2017淘宝新店如何推广 编辑:程序博客网 时间:2024/05/16 11:43
有时候会用到嵌套的列表(list),比如
方法有很多,目前了解到的各方面都比较好,也很pythonic的方法是:
[1, 2, [3, 4, [5, 6]], ["abc", "def"]]如果将嵌套的列表拉平(flatten)呢?变成:
[1, 2, 3, 4, 5, 6, "abc", "def"]
方法有很多,目前了解到的各方面都比较好,也很pythonic的方法是:
def flatten(l): for el in l: if hasattr(el, "__iter__") and not isinstance(el, basestring): for sub in flatten(el): yield sub else: yield el
l = [1, 2, [3, 4, [5, 6]], ["abc", "def"]] l2 = [x for x in flatten(l)] print l2 #[1, 2, 3, 4, 5, 6, "abc", "def"]
0 0
- Python如何拉平(flatten)嵌套列表(nested list)
- Python如何拉平(flatten)嵌套列表(nested list)--(递归生成器)
- LeetCode 341. Flatten Nested List Iterator(嵌套列表迭代器)
- *[Lintcode]Flatten Nested List Iterator 摊平嵌套的列表
- 528.Flatten Nested List Iterator-摊平嵌套的列表(中等题)
- LeetCode 114. Flatten Binary Tree to Linked List 拉平二叉树 Python Solution
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- Flatten Nested List Iterator
- 341. Flatten Nested List Iterator
- 341. Flatten Nested List Iterator
- 341. Flatten Nested List Iterator
- python编写shell脚本详细讲解
- 「简书」联合创始人赵波:不要活在烦恼里,逼自己做决定
- 世界级Oracle专家Jonathan Lewis:我很为DBA们的未来担心
- 王哲:爱偷懒+爱游戏=开源Cocos2d-x的生命基因
- 第四章 Windows游戏图形基础
- Python如何拉平(flatten)嵌套列表(nested list)
- Java_JavaEE_SSH_Struts2 Ajax支持闲谈;
- 用Vs2013+VELT-0.1.0进行Linux开发:环境搭建
- 10.2.3.2 在 C# 中以函数风格使用数组
- C++项目(续之)
- mysql之explain解析
- 小丽和小张 --- 作者:歪瓜裂枣
- 这是我的第一篇博客
- Yandex.Algorithm 2011 Qualification 2 A.(数学)