Python合并两个List

时间:2022-04-17 20:47:19

1.使用list的extend()方法,现有两个list分别为L1和L2:

1 >>> L1 = [1, 2, 3, 4, 5]
2 >>> L2 = [20, 30, 40]
3 >>> L1.extend(L2)
4 >>> L1
5 [1, 2, 3, 4, 5, 20, 30, 40]

2.用切片(slice)操作,L1[len(L1):len(L1)] = L2和上面的方法等价,例如:

1 >>> L1 = [1, 2, 3, 4, 5]
2 >>> L2 = [20, 30, 40]
3 >>> L1[len(L1):len(L1)] = L2
4 >>> 
5 >>> L1
6 [1, 2, 3, 4, 5, 20, 30, 40]

用切片方法的好处在于灵活,可以在任意节点进行插入,例如从头部插入:

1 >>> L1 = [1, 2, 3, 4, 5]
2 >>> L2 = [20, 30, 40]
3 >>> L1[0:0] = L2
4 >>> L1
5 [20, 30, 40, 1, 2, 3, 4, 5]

例如加到中间:

1 >>> L1 = [1, 2, 3, 4, 5]
2 >>> L2 = [20, 30, 40]
3 >>> 
4 >>> L1[1:1] = L2
5 >>> L1
6 [1, 20, 30, 40, 2, 3, 4, 5]