簡體   English   中英

如何在Python中使用分隔符連接列表列表

[英]How to join list of lists with separator in Python

如何使用分隔符加入列表列表。

例如

in:
list:
[[1,2], [3,4,5], [6,7]]

with separator:
0


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

例如,您的列表存儲在x

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

只需使用reduce with 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))

會給你帶來同樣的結果

我就是這樣做的:

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

最后一個[:-1]是刪除最后一個0

您可以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:的終止是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]

您可以將它與Python list 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM