Python 交错合并多个list列表的方法及示例代码

本文主要介绍Python中,多个list列表交错合并一个list列表的方法,以及相关的示例代码。

示例代码:

l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]

实现效果:

l5 = ["a",1,"w",5,"b",2,"x",6,"c",3,"y",7,"d",4,"z",8]

1、使用zip()实现

文档zip() 

l1 = ["a", "b", "c", "d"]
l2 = [1, 2, 3, 4]
l3 = ["w", "x", "y", "z"]
l4 = [5, 6, 7, 8]
l5 = [x for y in zip(l1, l2, l3, l4) for x in y] print(l5)

输出

['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]

2、使用itertools.chain() 和 zip()

相关文档itertools.chain 和 zip:

from itertools import chain
l1 = ["a", "b", "c", "d"]
l2 = [1, 2, 3, 4]
l3 = ["w", "x", "y", "z"]
l4 = [5, 6, 7, 8]
print(list(chain(*zip(l1, l2, l3, l4))))
#或者
print(list(chain.from_iterable(zip(l1, l2, l3, l4))))

3、使用itertools实现

文档itertool recipes 

from itertools import cycle, islice
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]

lists = [l1, l2, l3, l4]
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))
print(*roundrobin(*lists)) 

4、使用切片实现

l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
lists = [l1, l2, l3, l4]
lst = [None for _ in range(sum(len(l) for l in lists))]
for i, l in enumerate(lists):
    lst[i:len(lists)*len(l):len(lists)] = l
print(lst)

5、使用pandas实现

import pandas as pd
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
df = pd.DataFrame([l1 ,l2, l3, l4])
result = list(df.values.flatten('A'))
print(result)

6、使用numpy.dstack和flatten实现

import numpy as np
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
print(np.dstack((np.array(l1),np.array(l2),np.array(l3),np.array(l4))).flatten())
#或者
print(np.dstack((l1,l2,l3,l4)).flatten())

7、使用zip() 和 np.concatenate()实现

import numpy as np
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
l5 = np.concatenate(list(zip(l1, l2, l3, l4)))
print(l5)

8、使用zip()和reduce()

import functools, operator
l1 = ["a","b","c","d"]
l2 = [1,2,3,4]
l3 = ["w","x","y","z"]
l4 = [5,6,7,8]
print(functools.reduce(operator.add, zip(l1,l2,l3,l4)))
推荐阅读
cjavapy编程之路首页