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

时间:2014-06-09 08:59:23

标签: python list-comprehension

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

例如

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

with separator:
0


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

4 个答案:

答案 0 :(得分:8)

例如,您的列表存储在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))

将为您带来相同的结果

答案 1 :(得分:2)

我就是这样做的:

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

最后一次[:-1]是删除最后一项0

答案 2 :(得分:2)

您可以tee list作为可迭代,只有在有以下项目时才会生成分隔符。这里我们定义一个名为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]

答案 3 :(得分:0)

您可以将它与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]