【python】 合并列表的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014636245/article/details/87923458

python中利用非循环的方法将两个List列表中的内容进行合并

在处理字符串、目录和排序信息的时候,经常需要将两个列表进行合并。但利用for循环逐个插入会十分繁琐,利用下面的方法可以快速方便的进行列表内容的合并。

1.+运算直接合并

list_a = ['a','b','c']
list_b = ['d','e','f','g']
list_ab = list_a + list_b
print(list_ab)

>>> ['a', 'b', 'c', 'd', 'e', 'f', 'g']
由于列表可以保存各类对象,所以内容类型不同的列表也可以合并:

list_num = [1,2,3,4,5]
list_set = [{0},{1}]
list_dict = [{'key0':0},{'key1':1}]
list_mix = list_a + list_num + list_set + list_dict
print(list_mix)

>>> ['a', 'b', 'c', 1, 2, 3, 4, 5, set([0]), set([1]), {'key0': 0}, {'key1': 1}]

2.extend()方法

list_a = ['a','b','c']
list_b = ['d','e','f','g']
list_a.extend(list_b)
print(list_a)

>>> ['a', 'b', 'c', 'd', 'e', 'f', 'g']
这种方法直接在原有列表后加上了需要合并的新列表,扩增的原有的列表。
内存位置没有改变,内容被扩充,可以借助id()函数来查看:

list_a = ['a','b','c']
id1 = id(list_a)
list_b = ['d','e','f','g']
list_a.extend(list_b)
id2 = id(list_a)
print(id1==id2)

>>> True

3.基于slice的插入

list_a = ['a','b','c']
list_b = ['d','e','f','g']
list_a[0:0] = list_b    #列表中[n,n],表示在列表的第n+1个位置,将对应列表逐个元素插入合并
print(list_a)
#千万不能写成  list_a[0] = list_b,这会使得list_a[0]变为一个列表,而不是列表内的元素。

>>> ['d', 'e', 'f', 'g', 'a', 'b', 'c']

也可以修改位置,灵活变更合并的序列在原列表中的位置:

list_a = ['a','b','c']
list_b = ['d','e','f','g']
list_a[-1:-1] = list_b    #合并至最末尾
print(list_a)

>>> ['a', 'b', 'd', 'e', 'f', 'g', 'c']

合并到第二个位置:

list_a = ['a','b','c']
list_b = ['d','e','f','g']
list_a[1:1] = list_b   #合并至第二个位置
print(list_a)

>>> ['a', 'd', 'e', 'f', 'g', 'b', 'c']


*4.“指针”/解包操作

Python >= 3.5 PEP 448中可以使用*来进行类似指针的操作:

list_a = ['a','b','c']
list_b = ['d','e','f','g']
list_ab = [*list_a,*list_b]
print(list_ab)

>>> ['a', 'b', 'c', 'd', 'e', 'f', 'g']

ref:
https://www.jdoodle.com/python3-programming-online
https://www.tutorialspoint.com/index.htm
http://www.compileonline.com/index.htm
https://www.onlinegdb.com/online_python_interpreter
https://www.python.org/dev/peps/pep-0448/
https://stackoverflow.com/questions/1720421/how-to-concatenate-two-lists-in-python
https://blog.csdn.net/ppdyhappy/article/details/53213349
https://blog.csdn.net/fragmentalice/article/details/81363494
https://www.cnblogs.com/qingyuanjushi/p/8409949.html
https://blog.csdn.net/roytao2/article/details/54180182

在这里插入图片描述
picture from pexels.com

猜你喜欢

转载自blog.csdn.net/u014636245/article/details/87923458