# 压平列表

[[1, 2], [3, [4], [5, 6], 7], 8]

[1, 2, 3, 4, 5, 6, 7, 8]

1、使用sum和map，感觉玩的比较炫，大家来感受一下：

from collections import Iterable

def flatten(x):
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
return sum(map(flatten, x), [])
else:
return [x]

lst = [1, 2, [3, [4], [5, 6], 7], 8]
print(flatten(lst))

flat=lambda L: sum(map(flat,L),[]) if isinstance(L,list) else [L]

2、使用yield。这个是在《Python Cookbook》中介绍的一种方法

from collections import Iterable

def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x

items = [[1, 2], [3, [4], [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)

yield from 比较巧妙。不过，这里有个限制，yield from是python3才有的，如果是在python2中使用，需要这么写：

from collections import Iterable

def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
for i in flatten(x):
yield i
else:
yield x

items = [[1, 2], [3, [4], [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)

2和3通用。不得不说yield真是个好东西。

3、Tkinter自带函数_flatten。不说话，直接上代码

from Tkinter import _flatten
lst = [1, 2, [3, [4], [5, 6], 7], 8]
print(_flatten(lst))

def flatten(x):
for i in x:
if isinstance(i, Iterable) and not isinstance(i, (str, bytes)):
flatten(i)
else:
new_lst.append(i)

new_lst = []
lst = [1, 2, [3, [4], [5, 6], 7], 8]
flatten(lst)
print(new_lst)

（感谢群友提供）思路比较简单，代码也很清晰，只是全局列表到底还是感觉有一点点耍赖。

lst = [1, 2, [3, [4], [5, 6], 7], 8]
print(list("[" + str(lst).replace("[", "").replace("]", "") + "]"))

import re
lst = [1, 2, [3, [4], [5, 6], 7], 8]
print map(int, re.findall('\d+', str(lst)))

posted @ 2017-07-07 18:09  _小苹果  阅读(469)  评论(0编辑  收藏