Python合并两个List
1.使用list的extend()方法,现有两个list分别为L1和L2:
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1.extend(L2)
>>> L1
[1, 2, 3, 4, 5, 20, 30, 40]
2.用切片(slice)操作,L1[len(L1):len(L1)] = L2
和上面的方法等价,例如:
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1[len(L1):len(L1)] = L2
>>>
>>> L1
[1, 2, 3, 4, 5, 20, 30, 40]
用切片方法的好处在于灵活,可以在任意节点进行插入,例如从头部插入:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1[0:0] = L2
>>> L1
[20, 30, 40, 1, 2, 3, 4, 5]
例如加到中间:
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>>
>>> L1[1:1] = L2
>>> L1
[1, 20, 30, 40, 2, 3, 4, 5]