2014-06-09 92 views

回答

7

例如您的列表存儲在x

x=[[1,2], [3,4,5], [6,7]] 

只需使用reduce與lambda函數:

y=reduce(lambda a,b:a+[0]+b,x) 

現在y

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

或者你可以定義一個生成器功能:

def chainwithseperator(lis,sep): 
    it=iter(lis) 
    for item in it.next(): 
    yield item 
    for sublis in it: 
    yield sep 
    for item in sublis: 
     yield item 

現在呼籲:

y=list(chainwithseperator(x,0)) 

會帶給你不一樣的結果

+3

這是以二次方式運行的時間,因爲列表的'+'在參數大小的總和中以時間線性運行。 – user2357112

+0

我用'x = [[1,2]]''運行'[1,2,0]'是正確的結果,我不相信......與'x = [[1,2],[3,4,5]]相同' –

+0

@JonClements你是對的我解決了發生器中的問題,但它使得它更復雜一點 – Lee

2

這是我會怎麼做:

l = [[1,2], [3,4,5], [6,7]] 
result = [number for sublist in l for number in sublist+[0]][:-1] 

最後的[:-1]是刪除最後一個是0的項目。

0

您可以使用Python列表使用extend()方法:

orig_list = [[1,2], [3,4,5], [6,7]] 
out_list = [] 
for i in orig_list: 
    out_list.extend(i + [0]) 

# To remove the last element '0'. 
print my_list[:-1] 
2

可以teelist視爲可迭代,只產生分離時,有一個以下項目。在這裏我們定義了一個名爲joinlist功能包含發電機輔助函數來獲得相應的元素,然後返回使用chain.from_iterable所有這些元素的扁平列表:

from itertools import tee, chain 

def joinlist(iterable, sep): 
    def _yielder(iterable): 
     fst, snd = tee(iterable) 
     next(snd, []) 
     while True: 
      yield next(fst) 
      if next(snd, None): 
       yield [sep] 
    return list(chain.from_iterable(_yielder(iterable))) 

重要的是要注意重要的是終止了while True:發生在yield next(fst),因爲這會在某個時間點產生StopIteration並導致發生器退出。

x = [[1,2]] 
y = [[1, 2], [3,4,5]] 
z = [[1, 2], [3,4,5], [6, 7]] 

for item in (x, y, z): 
    print item, '->', joinlist(item, 0) 

# [[1, 2]] -> [1, 2] 
# [[1, 2], [3, 4, 5]] -> [1, 2, 0, 3, 4, 5] 
# [[1, 2], [3, 4, 5], [6, 7]] -> [1, 2, 0, 3, 4, 5, 0, 6, 7] 
相關問題