Python|一次附加多个列表
可能存在将 2-3 个列表的元素附加到一个列表的应用程序要求。这种应用程序有可能进入机器学习领域,有时也有可能进入 Web 开发领域。让我们讨论可以执行此特定任务的某些方式。
方法 #1:使用 +运算符
这可以使用加号运算符轻松完成,因为它在列表后面添加元素。在多个列表的情况下扩展了类似的逻辑。
Python3
# Python3 code to demonstrate
# adding multiple list at once
# using + operator
# initializing lists
test_list1 = [1, 3, 5, 5, 4]
test_list2 = [4, 6, 2, 8, 10]
test_list3 = [7, 5, 2, 9, 11]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
print ("The original list 3 is : " + str(test_list3))
# using + operator
# adding multiple list at once
test_list1 = test_list1 + test_list2 + test_list3
# printing result
print ("The extended and modified list is : " + str(test_list1))
Python3
# Python3 code to demonstrate
# adding multiple list at once
# using itertools.chain()
from itertools import chain
# initializing lists
test_list1 = [1, 3, 5, 5, 4]
test_list2 = [4, 6, 2, 8, 10]
test_list3 = [7, 5, 2, 9, 11]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
print ("The original list 3 is : " + str(test_list3))
# using itertools.chain()
# adding multiple list at once
test_list1 = list(chain(test_list1, test_list2, test_list3))
# printing result
print ("The extended and modified list is : " + str(test_list1))
输出:
The original list 1 is : [1, 3, 5, 5, 4]
The original list 2 is : [4, 6, 2, 8, 10]
The original list 3 is : [7, 5, 2, 9, 11]
The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]
方法 #2:使用 itertools.chain()
链函数也可用于执行此特定任务,因为它使用迭代器执行此操作,因此提供比上述方法更好的性能。
Python3
# Python3 code to demonstrate
# adding multiple list at once
# using itertools.chain()
from itertools import chain
# initializing lists
test_list1 = [1, 3, 5, 5, 4]
test_list2 = [4, 6, 2, 8, 10]
test_list3 = [7, 5, 2, 9, 11]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
print ("The original list 3 is : " + str(test_list3))
# using itertools.chain()
# adding multiple list at once
test_list1 = list(chain(test_list1, test_list2, test_list3))
# printing result
print ("The extended and modified list is : " + str(test_list1))
输出:
The original list 1 is : [1, 3, 5, 5, 4]
The original list 2 is : [4, 6, 2, 8, 10]
The original list 3 is : [7, 5, 2, 9, 11]
The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]