📜  Python|一次迭代两个列表

📅  最后修改于: 2022-05-13 01:54:31.538000             🧑  作者: Mango

Python|一次迭代两个列表

有时,在使用Python列表时,我们可能会遇到必须遍历两个列表元素的问题。一个接一个地迭代是一种选择,但它更麻烦,总是建议使用一对二的衬垫。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环+“+”运算符
上述功能的组合可以使我们的任务更容易。但是这里的缺点是我们可能必须连接列表,因此会消耗比预期更多的内存。

# Python3 code to demonstrate working of
# Iterating two lists at once
# using loop + "+" operator
  
# initializing lists
test_list1 = [4, 5, 3, 6, 2]
test_list2 = [7, 9, 10, 0]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Iterating two lists at once
# using loop + "+" operator
# printing result 
print("The paired list contents are : ")
for ele in test_list1 + test_list2:
    print(ele, end =" ")
输出 :
The original list 1 is : [4, 5, 3, 6, 2]
The original list 2 is : [7, 9, 10, 0]
The paired list contents are : 
4 5 3 6 2 7 9 10 0 

方法#2:使用chain()
这是类似于上述方法的方法,但它的内存效率稍高一些,因为chain()用于执行任务并在内部创建一个迭代器。

# Python3 code to demonstrate working of
# Iterating two lists at once
# using chain()
from itertools import chain
  
# initializing lists
test_list1 = [4, 5, 3, 6, 2]
test_list2 = [7, 9, 10, 0]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Iterating two lists at once
# using chain()
# printing result 
print("The paired list contents are : ")
for ele in chain(test_list1, test_list2):
    print(ele, end =" ")
输出 :
The original list 1 is : [4, 5, 3, 6, 2]
The original list 2 is : [7, 9, 10, 0]
The paired list contents are : 
4 5 3 6 2 7 9 10 0