Re: [問題] 請教 List 問題
※ 引述《plom (plom)》之銘言:
: 請教各位了,
: 假設有一個 List =[['ac','bc'],['cd','de','ef']]
: 如何簡潔語法可以將它解開成:['ac','bc','cd','de','ef']?
這問題可以一般化為 flatten list in python .
把 keyword 丟上 google 可以查到不少解法,如
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
result = []
for el in x:
#if isinstance(el, (list, tuple)):
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.76.240.242
→
01/20 21:23, , 1F
01/20 21:23, 1F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章