# 生成器版本
def flatten(lst):
for item in lst:
if isinstance(item, collections.Iterable) and not isinstance(item, (str, bytes)):
yield from flatten(item)
else:
yield item
# 普通版本
def flatten(lst):
result = []
def fly(lst):
for item in lst:
if isinstance(item, collections.Iterable) and not isinstance(item, (str, bytes)):
fly(item)
else:
result.append(item)
def flatten(seq):
l = []
for elt in seq:
t = type(elt)
if t is tuple or t is list:
for elt2 in flatten(elt):
l.append(elt2)
else:
l.append(elt)
return l
def flat(a):
b = []
for each in a:
if not isinstance(each, list):
b.append(each)
else:
b.extend(flat(each))
return b
print(flat(a))
《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, igore_types):
yield from flatten(x)
else:
yield x
最後這個答案值得一提的還有使用了 yield from 來進行遞歸,讓整個函數非常簡潔優美。如果對yield from 語句不熟的可以看看《流暢的Python》里流程式控制制那一章,裡面有更多關於yield 語句的介紹。
哪需要生成器、遞歸什麼的,,
簡單問題暴力一點好了
In [82]: a = [[], 1, [20, 300], [[4000, 50000, 600000]]]
...: b = str(a).replace("[", "").replace("]", "").replace(" ", "")
...: c = [eval(i) for i in b.split(",") if i != ""]
...: print(c)
...:
[1, 20, 300, 4000, 50000, 600000]
Obviously this doesn"t work if any of the strings contain [].
剛好前幾天自己寫了一個,最好使用yield from(是不是叫遞歸生成器?)
手機回答,自己看文檔,裡面有我的垃圾代碼
https://github.com/Zousiyu/code_snippet
論優雅,還是生成器優雅,而且在序列非常大的時候,生成器這種惰性序列是有絕對優勢的。
from collections import Iterable
def unfold(items, ignore_types=(str, bytes)):
for item in items:
if isinstance(item, Iterable) and not isinstance(item, ignore_types):
yield from unfold(item)
else:
yield item
如果序列的深度和大小很平常,不至於達到以百萬計的級別,遞歸實現也行
from collections import Iterable
def unfold(items, ignore_types=(str, bytes)):
unfolded = []
for item in items:
if isinstance(item, Iterable) and not isinstance(item, ignore_types):
unfolded.extend(unfold(item))
else:
unfolded.append(item)
return unfolded
np的reshape很奇怪,我在這寫了個錯的也有人贊。
想問有沒有c++版本
import numpy as nplst = np.hstack(lst).tolist()
額,難道不是序列解包??最快沒有之一
def lowest(List=list):
l=[]
def lower(List = list):
for i in List:
if isinstance(i,list):
lower(i)
else:
l.append(i)
lower(List)
return l
最近在做CS61a的題目時有遇到過,沒用yield,遞歸一下
def flatten(lst):
"""Returns a flattened version of lst.
&>&>&> flatten([1, 2, 3]) # normal list
[1, 2, 3]
&>&>&> x = [1, [2, 3], 4] # deep list
&>&>&> flatten(x)
[1, 2, 3, 4]
&>&>&> x = [[1, [1, 1]], 1, [1, 1]] # deep list
&>&>&> flatten(x)
[1, 1, 1, 1, 1, 1]
"""
if not lst:
return []
elif type(lst[0]) == list:
return flatten(lst[0]) + flatten(lst[1:])
else:
return [lst[0]] + flatten(lst[1:])