如何扁平化嵌套列表并用分隔符连接

6 投票
4 回答
4447 浏览
提问于 2025-04-18 09:06

如何用分隔符连接多个列表?

举个例子:

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

带有分隔符:

0

结果:

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

4 个回答

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

你可以把 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]
2

这是我会这样做的:

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

最后的 [:-1] 是用来去掉最后一个元素的,这个元素是 0

11

比如说,你的列表保存在 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))

会得到相同的结果。

撰写回答