用Python连接列表的6种方法

时间:2020-02-23 14:42:12  来源:igfitidea点击:

在本教程中,我们将揭示在Python中连接列表的不同方法。
Python列表用于存储同类元素并对其进行操作。

通常,串联是指以端到端的方式连接特定数据结构的元素的过程。

以下是在Python中串联列表的6种方法。

  • 串联(+)运算符
  • 天真的方法
  • 列表理解
  • extend()方法
  • " *"运算符
  • itertools.chain()方法

1.用于列表串联的串联运算符(+)

" +"运算符可以用来连接两个列表。
它在另一个列表的末尾追加一个列表,并产生一个新列表作为输出。

例:

list1 = [10, 11, 12, 13, 14] 
list2 = [20, 30, 42] 

res = list1 + list2 

print ("Concatenated list:\n" + str(res)) 

输出:

Concatenated list:
[10, 11, 12, 13, 14, 20, 30, 42]

2.列表连接的简单方法

在朴素方法中,使用for循环遍历第二个列表。
此后,第二个列表中的元素将附加到第一个列表中。
第一个列表结果是第一个列表和第二个列表的串联。

例:

list1 = [10, 11, 12, 13, 14] 
list2 = [20, 30, 42] 

print("List1 before Concatenation:\n" + str(list1))
for x in list2 : 
  list1.append(x) 

print ("Concatenated list i.e. list1 after concatenation:\n" + str(list1)) 

输出:

List1 before Concatenation:
[10, 11, 12, 13, 14]
Concatenated list i.e. list1 after concatenation:
[10, 11, 12, 13, 14, 20, 30, 42]

3.列表理解以连接列表

Python List Comprehension是在Python中连接两个列表的替代方法。
列表理解基本上是基于现有列表构建/生成元素列表的过程。

它使用for循环以元素方式处理和遍历列表。
下面的内联for循环等效于嵌套的for循环。

例:

list1 = [10, 11, 12, 13, 14] 
list2 = [20, 30, 42] 

res = [j for i in [list1, list2] for j in i] 

print ("Concatenated list:\n"+ str(res)) 

输出:

Concatenated list:
 [10, 11, 12, 13, 14, 20, 30, 42]

4,用于列表串联的Pythonextend()方法

Python的extend()方法可用于连接Python中的两个列表。
extend()函数对传递的参数进行迭代,并将该项添加到列表中,从而以线性方式扩展列表。

语法:

list.extend(iterable)

例:

list1 = [10, 11, 12, 13, 14] 
list2 = [20, 30, 42] 
print("list1 before concatenation:\n" + str(list1))
list1.extend(list2) 
print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1)) 

list2的所有元素都附加到list1上,因此list1得到更新,结果作为输出。

输出:

list1 before concatenation:
[10, 11, 12, 13, 14]
Concatenated list i.e ,ist1 after concatenation:
[10, 11, 12, 13, 14, 20, 30, 42]

5.用于列表串联的Python" *"运算符

Python的'*'运算符可用于轻松地将Python中的两个列表连接起来。

Python中的" *"运算符基本上将索引参数处的项目集合解压缩。

例如:考虑一个列表my_list = [1、2、3、4]。

语句* my_list会将列表替换为其索引位置的元素。
因此,它解压缩了列表中的项目。

例:

list1 = [10, 11, 12, 13, 14] 
list2 = [20, 30, 42] 

res = [*list1, *list2] 

print ("Concatenated list:\n " + str(res)) 

在上面的代码片段中,语句res = [* list1,* list2]用给定顺序的项(即list1的元素在list2的元素之后)替换list1和list2。
这将执行串联并产生以下输出。

输出:

Concatenated list:
 [10, 11, 12, 13, 14, 20, 30, 42]

6. Python itertools.chain()方法来连接列表

Python itertools模块的itertools.chain()函数还可用于连接Python中的列表。

" itertools.chain()"函数接受不同的可迭代变量(例如列表,字符串,元组等)作为参数,并给出它们的序列作为输出。

结果是线性序列。
元素的数据类型不会影响chain()方法的功能。

例如:语句itertools.chain([1,2],['John','Bunny'])将产生以下输出:1 2 John Bunny

例:

import itertools
list1 = [10, 11, 12, 13, 14] 
list2 = [20, 30, 42] 

res = list(itertools.chain(list1, list2)) 
 

print ("Concatenated list:\n " + str(res)) 

输出:

Concatenated list:
 [10, 11, 12, 13, 14, 20, 30, 42]