---
title: "Python如何拉平（flatten）嵌套列表(nested list)"
author: "GhostFromheaven"
date: "2012-06-15T00:23:35Z"
tags: []
categories: ["编程语言"]
slug: "python-flatten-nested-list"
draft: false
lastmod: "2012-06-15T00:25:42Z"
id: 1561340
url: "https://ghostfromheaven.iteye.com/blog/1561340"
---

有时候会用到嵌套的列表(list)，比如

```
[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"]
```