在本教程中,我们将介绍在Python中连接列表的不同方法。PYTHON Lists用于存储同构元素并对其执行操作。
一般而言,连接是以端到端的方式连接特定数据结构的元素的过程。
下面是在Python中连接列表的6种方法。
- 串联(+)运算符
- 天真方法
- 列表理解
- EXTEND()方法
- ‘ ’运算符*
- itertools.chain()方法
1.列表拼接运算符(+)
‘+’运算符
可用于连接两个列表。它将一个列表追加到另一个列表的末尾,并生成一个新列表作为输出。
示例:
1list1 = [10, 11, 12, 13, 14]
2list2 = [20, 30, 42]
3
4res = list1 + list2
5
6print ("Concatenated list:\n" + str(res))
输出:
1Concatenated list:
2[10, 11, 12, 13, 14, 20, 30, 42]
2.列表拼接的朴素方法
在朴素的方法中,使用了for循环来遍历第二个列表。在此之后,第二个列表中的元素被追加到第一个列表中。第一个列表 结果是第一个列表和第二个列表的串联。
示例:
1list1 = [10, 11, 12, 13, 14]
2list2 = [20, 30, 42]
3
4print("List1 before Concatenation:\n" + str(list1))
5for x in list2 :
6 list1.append(x)
7
8print ("Concatenated list i.e. list1 after concatenation:\n" + str(list1))
输出:
1List1 before Concatenation:
2[10, 11, 12, 13, 14]
3Concatenated list i.e. list1 after concatenation:
4[10, 11, 12, 13, 14, 20, 30, 42]
3.连接列表的列表解析
PYTHON LIST Comprehension是连接PYTHON中两个列表的替代方法。列表理解基本上是基于现有列表构建/生成元素列表的过程。
它使用for循环以元素方式处理和遍历列表。下面的内联for循环等同于嵌套的for循环。
示例:
1list1 = [10, 11, 12, 13, 14]
2list2 = [20, 30, 42]
3
4res = [j for i in [list1, list2] for j in i]
5
6print ("Concatenated list:\n"+ str(res))
输出:
1Concatenated list:
2 [10, 11, 12, 13, 14, 20, 30, 42]
4.列表拼接的扩展()方法
可以使用Python的end()方法来连接Python中的两个列表。end()
函数对传递的参数进行迭代,并将项添加到列表中,从而以线性方式扩展列表。
语法:
1list.extend(iterable)
示例:
1list1 = [10, 11, 12, 13, 14]
2list2 = [20, 30, 42]
3print("list1 before concatenation:\n" + str(list1))
4list1.extend(list2)
5print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1))
List2的所有元素都被附加到List1,因此List1得到更新,并将结果作为输出。
输出:
1list1 before concatenation:
2[10, 11, 12, 13, 14]
3Concatenated list i.e ,ist1 after concatenation:
4[10, 11, 12, 13, 14, 20, 30, 42]
5.列表拼接的Python‘* ’运算符
可以使用Python的‘’* ‘运算符
轻松地将两个列表连接起来。
Python中的‘* ’操作符基本上 在索引参数处** 解包项目集合** 。
例如:考虑一个列表my_list=[1,2,3,4]。
语句 * my_list 将** 用索引位置上的元素替换列表 ** 。因此,它解包列表中的项。
示例:
1list1 = [10, 11, 12, 13, 14]
2list2 = [20, 30, 42]
3
4res = [*list1, *list2]
5
6print ("Concatenated list:\n " + str(res))
在上面的代码片段中,语句 res = [ ** list1, list2]** 将list1和list2替换为给定顺序的项目,即list1的元素在list2的元素之后。这将执行连接并产生以下输出。
输出:
1Concatenated list:
2 [10, 11, 12, 13, 14, 20, 30, 42]
6. Python itertools.chain()方法连接列表
PythonIterTools模块的[itertools.chain()](/community/tutorials/python-itertools# python-itertools-chain)函数也可以用来连接Python中的列表。
函数的作用是:接受不同的可迭代变量,如列表、字符串、元组等作为参数,并给出它们的序列作为输出。
结果是它是一个线性序列。元素的数据类型不会影响chain()方法的功能。
例如:语句itertools.chain([1,2],[‘John’,‘Bunny’]) 将产生以下输出:** 1 2 John Bunny**
示例:
1import itertools
2list1 = [10, 11, 12, 13, 14]
3list2 = [20, 30, 42]
4
5res = list(itertools.chain(list1, list2))
6
7print ("Concatenated list:\n " + str(res))
输出:
1Concatenated list:
2 [10, 11, 12, 13, 14, 20, 30, 42]
结论
因此,在本文中,我们了解并实现了在Python中连接列表的不同方法。