碾平列表是個很好玩的函數。好比你有個嗷嗷噁心的列表:html
[[1, 2], [3, [4], [5, 6], 7], 8]
你想把它變成正常一點的python
[1, 2, 3, 4, 5, 6, 7, 8]
要怎麼辦呢?linux
老實說,好久不接觸這種東西,我已經早忘了當初是怎麼寫的了,憋了半天沒寫出來,後來參考了 http://www.cnblogs.com/c-hy/archive/2012/09/21/2696703.html 纔回憶起來。windows
而後,着重介紹三種方法:app
一、使用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))
剛纔那個網頁中說,國外某論壇的大神寫了一個匿名函數spa
flat=lambda L: sum(map(flat,L),[]) if isinstance(L,list) else [L]
基本上是一個意思的。code
二、使用yield。這個是在《Python Cookbook》中介紹的一種方法htm
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中使用,須要這麼寫:blog
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真是個好東西。
三、Tkinter自帶函數_flatten。不說話,直接上代碼
from Tkinter import _flatten lst = [1, 2, [3, [4], [5, 6], 7], 8] print(_flatten(lst))
這個就比較可怕了。不過Tkinter這東西,聽說只有windows纔有,linux沒有。mac不太清楚。
固然,其餘方法也是有的,好比
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)))
哈哈,很特定的環境下可使用,好比第一個列表元素中不能含有"["和"]",第二個更是隻能包含整數。不過,同窗們的腦洞仍是比較大的。
記錄一下,留着玩。