Python 合并list 11种方式

邱秋 • 2019年08月22日 • 阅读:140 • python

Python 交错合并多个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、直接使用"+"号合并列表

l5 = l1 + l2 + l3 + l4 

2、使用extend方法

l5 = l1.extend(l2,l3,l4,l5)  

3、使用append方法

aList = [1,2,3]
bList = ['www', 'jb51.net']
aList.append(bList)
print(aList)

# 输出:

[1, 2, 3, ['www', 'jb51.net']]

4、使用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]

5、使用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))))

6、使用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)) 

7、使用切片实现

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)


# demo1
aList = [1,2,3]
bList = ['www', 'jb51.net']
aList[len(aList):len(aList)] = bList
print(aList)
# 输出:
[1, 2, 3, 'www', 'jb51.net']

# demo2
aList = [1,2,3]
bList = ['www', 'jb51.net']
aList[1:1] = bList
print(aList)
# 输出为:

[1, 'www', 'jb51.net', 2, 3]

8、使用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)

9、使用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())

10、使用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)

11、使用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)))

我,秦始皇,打钱!