当前位置:   article > 正文

Python:合并两个list[]_python两个list合并成一个list

python两个list合并成一个list

Python:合并两个list[]

Created: January 24, 2022 9:58 PM

今天在开发的时候,遇到一个问题,就是将两个python 的list对象数据进行合并,有如下方法可以解决。

1 利用操作符号+

例如:

In [2]: list2 = ['hello', 'world', 'combine']

In [3]: list3 = list1 + list2

In [4]: list3

Out[4]: ['a', 'b', 1, 2, 3, 'hello', 'world', 'combine']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2 利用extend()

接上面的运算,这里在定义一个tmp,值为list1的值,这里使用extend,将list2 的数据和tmp的数据进行合并,之后输出tmp 和list1,结果都是一样的。

所以这里有一个知识点,就是 = 是浅拷贝,就是只拷贝这个对象的引用。

In [5]: tmp = list1

In [6]: tmp
Out[6]: ['a', 'b', 1, 2, 3]

In [7]: tmp.extend(list2)

In [8]: tmp
Out[8]: ['a', 'b', 1, 2, 3, 'hello', 'world', 'combine']

In [9]: list1
Out[9]: ['a', 'b', 1, 2, 3, 'hello', 'world', 'combine']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这里我们使用copy 中的深拷贝,在重复上面的操作,大家可以看出差别

# 分割线
In [10]: import copy

In [11]: tmp2 = copy.deepcopy(list2)

In [12]: tmp2.extend(list2)

In [13]: tmp2
Out[13]: ['hello', 'world', 'combine', 'hello', 'world', 'combine']

In [14]: list2
Out[14]: ['hello', 'world', 'combine']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

3 利用append()

利用append就不算两个list对象的操作了,但是也可以了解这个用法。

In [15]: list2
Out[15]: ['hello', 'world', 'combine']

In [16]: list2.append('girl')

In [17]: list2
Out[17]: ['hello', 'world', 'combine', 'girl']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/759584
推荐阅读
相关标签
  

闽ICP备14008679号