📜  Python - 交错两个不同长度的列表

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

Python - 交错两个不同长度的列表

给定两个不同长度的列表,任务是编写一个Python程序来交替获取它们的元素,并重复较小列表的列表元素,直到用尽较大的列表元素。

例子:

方法 #1:使用zip() + cycle() +列表理解

在这种情况下,较小列表中元素的重复使用 cycle() 处理,连接使用 zip() 完成。列表理解同时执行交错任务。

Python3
# Python3 code to demonstrate working of
# Repetitive Interleave 2 lists
# Using zip() + cycle() + list comprehension 
from itertools import cycle
  
# initializing lists
test_list1 = list('abc')
test_list2 = [5, 7, 3, 0, 1, 8, 4]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# zip() combining list, after Repetitiveness using cycle()
res = [ele for comb in zip(cycle(test_list1), test_list2) for ele in comb]
  
# printing result
print("The interleaved list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Repetitive Interleave 2 lists
# Using chain() + zip() + cycle()
from itertools import cycle, chain
  
# initializing lists
test_list1 = list('abc')
test_list2 = [5, 7, 3, 0, 1, 8, 4]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# zip() combining list, after Repetitiveness using cycle()
# chain() gets interleaved done
res = list(chain(*zip(cycle(test_list1), test_list2)))
  
# printing result
print("The interleaved list : " + str(res))


输出:

方法#2:使用chain() + zip() + cycle()

大多数操作与上述方法相同,唯一的区别是使用 chain() 执行交错任务。

蟒蛇3

# Python3 code to demonstrate working of
# Repetitive Interleave 2 lists
# Using chain() + zip() + cycle()
from itertools import cycle, chain
  
# initializing lists
test_list1 = list('abc')
test_list2 = [5, 7, 3, 0, 1, 8, 4]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# zip() combining list, after Repetitiveness using cycle()
# chain() gets interleaved done
res = list(chain(*zip(cycle(test_list1), test_list2)))
  
# printing result
print("The interleaved list : " + str(res))

输出: