標籤:

如何把嵌套的python list轉成一個一維的python list?

a = [[1,2,3], [5, 2, 8], [7,8,9]], 想把a變成[1,2,3, 5, 2, 8, 7,8,9]


python2的話

&>&>&> from compiler.ast import flatten
&>&>&> flatten(a)


來個簡單點的

或者:

import itertools
a = [[1,2,3],[4,5,6], [7], [8,9]]
out = list(itertools.chain.from_iterable(a))


reduce(lambda x,y:x+y, a)


import operator
from functools import reduce
a = [[1,2,3], [4,5,6], [7,8,9]]
print(reduce(operator.add, a))


最符合直覺的不應該是把沒用的方括弧去掉么(逃

a = eval("[%s]"%repr(l).replace("[", "").replace("]", ""))


謝邀。

方式比較多,遞歸比較容易懂:

def expand_list(nested_list):
for item in nested_list:
if isinstance(item, (list, tuple)):
for sub_item in expand_list(item):
yield sub_item
else:
yield item

print list(expand_list([[1,2,3], [5, 2, 8], [7,8,9]]))


來個one-line的版本,可以展開任意深度的嵌套 |??)

from collections import Iterable

flat = lambda t: [x for sub in t for x in flat(sub)] if isinstance(t, Iterable) else [t]

In [1]: flat([1,2,[3,4,[5]],[6,7]])
Out[1]: [1, 2, 3, 4, 5, 6, 7]

或者用Generator版本:

flat = lambda t: (x for sub in t for x in flat(sub)) if isinstance(t, Iterable) else iter((t,))

In [2]: flat([[7,6],[5,[4,[3]], [2,1]]])
Out[2]: & at 0x000000000410CAB0&>

In [3]: list(_)
Out[3]: [7, 6, 5, 4, 3, 2, 1]

--------------------------分-------------------割--------------------線---------------------------

如果用寬度優先展開嵌套呢?( ???)

......

先仔細觀察深度優先迭代的標準型:

def flat_depth(tree):
if not isinstance(tree, Iterable):
yield tree
else:
for sub in tree:
for x in flat_depth(sub):
yield x

思考中)那如果需要寬度優先,是不是可以讓else分支里,tree裡面的每個分支排一下隊?

諾~

def flat_breadth(tree):
if not isinstance(tree, Iterable):
yield tree
else:
for x in zipper(map(flat_breadth, tree)):
yield x

那麼問題來了 --

What &TF& is zipper?

-- zipper就是一個隊列處理器,輸入一系列迭代器,它來處理輪流迭代的循環。

from collections import deque

def zipper(itrs):
q = deque(itrs)
while q:
itr = q.popleft()
try:
yield next(itr)
q.append(itr)
except StopIteration:
pass

隨意感受一下:

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

# 深度優先
In [1]: list(flat_depth(b))
Out[1]: [1, 2, 3, 4, 5, 6, 7, 8]

# 寬度優先
In [2]: list(flat_breadth(b))
Out[2]: [1, 2, 4, 3, 5, 7, 6, 8]

答非所問的地方還望題主見諒( ??。)

---


如何把嵌套的python list轉成一個一維的python list? - 郝小胖的回答

對字元串的支持有問題,上面的回答大多都是深度優先的版本,我來提供一個 簡單粗暴 廣度 優先展開 非遞歸 的 版本 , 只用到python內置函數,不依賴任何庫 :

def flap(*a):
"""Breadth-First Traversal"""
a=list(a);r=[];i=0
while -1&

時間複雜度 o(n) ,最壞情況下空間複雜度o(n^2)


適合字元和數字情況,並且支持多層嵌套的來一個:

def flat(l):
for k in l:
if not isinstance(k, (list, tuple)):
yield k
else:
yield from flat(k)

結果:

&>&>&> a = ["參與/A", ["北京/G", "電影/C", "學院/D"], "和/X", ["美國/G", "辛普森/F", "公司/D"], "的/B", "活動/Z", ",/Z", "由/A", ["交通/C", "銀行/D", "北京/G", "分行/D"], "與/X", "麥當勞/K", "贊助/B", ",/A", ["巴/J", "政府/D"], "和/X", ["中共中央/K", "顧問/K", "委員會/D"], "指導/B", ",/A", ["中央/C", "電視台/D"], "報道/B"]
&>&>&> list(flat(a))
["參與/A", "北京/G", "電影/C", "學院/D", "和/X", "美國/G", "辛普森/F", "公司/D", "的/B", "活動/Z", ",/Z", "由/A", "交通/C", "銀行/D", "北京/G", "分行/D", "與/X", "麥當勞/K", "贊助/B", ",/A", "巴/J", "政府/D", "和/X", "中共中央/K", "顧問/K", "委員會/D", "指導/B", ",/A", "中央/C", "電視台/D", "報道/B"]

&>&>&>list(flat([[1,[2,3]], [5, 2, [8]], [7,8,9]]))
[1, 2, 3, 5, 2, 8, 7, 8, 9]


&>&>&> import itertools
&>&>&> list(itertools.chain.from_iterable(a))


func = lambda x: [y for l in x for y in func(l)] if type(x) is list else [x]
result = func(target_list)

可以展開任意維

誠如諸位所說,這種問題就是 let me google it for you 的問題


提問之前最好Stackoverflow找找,

flatten list python 基本就可以得到答案了.

# flatten
[item for sublist in list for item in sublist]


提問之前最好Google一下!

Python壓平嵌套列表


《python基礎教程》


ab = [[1,2,3], [5, 2, 8], [7,8,9]]
print([i for item in ab for i in item ])


def fun(li,em=[]): #優雅滴寫法,包治各種嵌套
for x in li:
if type(x)!=list:
em.append(x)
else:
fun(x)
return em


只適用於list和tuple:

def flat(l):
def iter(l):
if isinstance(l, (list, tuple)):
for k in l:
for v in iter(k):
yield v
else:
yield l
if l is None:
return None
return list(iter(l))

但是對於自包含或遞歸包含的列表誤解,會陷入死循環的。


a = [[1,2,3], [4,5,6], [7,8,9]]

extend_a = [number for inner_list in a for number in inner_list]


最簡單的方法,用 numpy.ravel()。

a = [[1,2,3], [5, 2, 8], [7,8,9]]

list(np.ravel(a))

得到:

[1, 2, 3, 5, 2, 8, 7, 8, 9]


a = [[1,2,3], [5, 2, 8], [7,8,9]]
l=[]
for m in range(0,3):
for i in a[m]:
l.append(i)
print(l)


推薦閱讀:

為什麼說 Python 是強類型語言?
C/C++ 這類更底層的語言,如果把平時常用的高級函數和功能都實現,能否達到 Python 的開發效率?
python 的絕對優勢在哪些方向?
學習編程,如果只看"工程類"書籍,不看"科學類『書籍,會有哪些不良後果?
個人充電,想學一門替代python的語言?

TAG:Python |