Python列表操作
Python添加列表
4 分钟阅读
在 Python 操作列表有各种方法。例如 – 简单地将一个列表的元素附加到 for 循环中另一个列表的尾部,或使用 +/* 运算符、列表推导、extend() 和 itertools.chain() 方法。
Python 添加列表 – 6 种连接/连接列表的方法
用于添加两个列表的 for 循环
这是添加两个列表的最直接的编程技术。
- 使用 for 循环遍历第二个列表
- 保留在第一个列表中附加元素
- 第一个列表将动态扩展
# Python Add lists example
# Sample code to add two lists using for loop
# Test input lists
in_list1 = [21, 14, 35, 16, 55]
in_list2 = [32, 25, 71, 24, 56]
# Using for loop to add lists
for i in in_list2 :
in_list1.append(i)
# Displaying final list
print ("\nResult: **********\nConcatenated list using for loop: "
+ str(in_list1))
加号 (+) 运算符以合并两个列表
许多语言使用 + 运算符来追加/合并字符串。Python也支持它,甚至支持列表。
这是一个使用“+”运算符的简单合并操作。您可以通过将一个列表添加到另一个列表的背面来轻松合并列表。
# Sample code to merge two lists using + operator
# Test input lists
in_list1 = [21, 14, 35, 16, 55]
in_list2 = [32, 25, 71, 24, 56]
in_list3 = in_list1 + in_list2
# Displaying final list
print ("\nResult: **********\nPython merge list using + operator: "
+ str(in_list3))
用于联接列表的 Mul (*) 运算符
这是一种连接两个或多个列表的全新方法,可从 Python 3.6 获得。您可以应用它来连接多个列表并一个统一列表。
# Python join two lists
# Sample code to join lists using * operator
# Test input lists
in_list1 = [21, 14, 35, 16, 55]
in_list2 = [32, 25, 71, 24, 56]
in_list3 = [*in_list1, *in_list2]
print ("\nResult: **********\nPython join list using * operator: "
+ str(in_list3))
列表推导以连接列表
列表推导允许对输入列表进行任何操作(串联),并且可以毫不费力地生成一个新操作。此方法像在“for”循环中一样处理列表,即逐个元素。
in_list1 = [21, 14, 35, 16, 55]
in_list2 = [32, 25, 71, 24, 56]
in_list3 = [n for m in [in_list1, in_list2] for n in m]
print ("\nResult: **********\nPython concatenate list using list comprehension: "
+ str(in_list3))
内置列表扩展() 方法
此函数是 Python 列表类的一部分,也可用于添加或合并两个列表。它对原始列表进行就地扩展。
in_list1 = [21, 14, 35, 16, 55]
in_list2 = [32, 25, 71, 24, 56]
in_list1.extend(in_list2)
print ("\nResult: **********\nPython Add lists using list.extend(): "
+ str(in_list1))
itertools.chain() 来组合列表
Python itertools chain() 函数接受多个可迭代对象并生成单个列表。输出是将所有输入列表串联为一个。
import itertools
# Test input lists
in_list1 = [21, 14, 35, 16, 55]
in_list2 = [32, 25, 71, 24, 56]
in_list3 = list(itertools.chain(in_list1, in_list2))
print ("\nResult: **********\nPython join lists using itertools.chain(): "
+ str(in_list3))