当前位置:   article > 正文

python 合并list的四种方法_python list合并

python list合并

1 运算法+

list_a = ['a','b','c']
list_b = [1,2,3,4]
list_ab = list_a + list_b
print(list_ab)
  • 1
  • 2
  • 3
  • 4

结果:

['a', 'b', 'c', 1, 2, 3, 4]
  • 1

列表可以保存各种类型对象,所以内容类型不同的列表也可以合并

2 extend() 方法

直接在原有list上进行扩充

list_a = ['a','b','c']
list_b = [1,2,3,4]
list_a.extend(list_b)
print(list_a)
  • 1
  • 2
  • 3
  • 4

结果

['a', 'b', 'c', 1, 2, 3, 4]
  • 1

3 基于切片的形式

list_a = ['a','b','c']
list_b = [1,2,3,4]
list_a[0:0] = list_b
print(list_a)
list_a[-1:-1] = list_b
print(list_a)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

结果:

[1, 2, 3, 4, 'a', 'b', 'c']
[1, 2, 3, 4, 'a', 'b', 1, 2, 3, 4, 'c']
  • 1
  • 2

4 解指针的方式

list_a = ['a','b','c']
list_b = [1,2,3,4]
print([*list_a,*list_b])
  • 1
  • 2
  • 3

结果:

['a', 'b', 'c', 1, 2, 3, 4]
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/759592
推荐阅读
相关标签
  

闽ICP备14008679号