📜  Python – 交叉连接每个 Kth 段

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

Python – 交叉连接每个 Kth 段

给定两个列表,在每个 Kth 位置提取替代元素。

方法 #1:使用生成器 [yield] + 循环

在此,我们迭代所有元素,嵌套以在每次遍历时从两个列表中获取 K 个元素。产量用于在处理段时动态返回段。

Python3
# Python3 code to demonstrate working of
# Cross Join every Kth segment
# Using yield + loop
 
# helper function
def pair_merge(test_list1, test_list2, K):
    idx1 = 0
    idx2 = 0
    while(idx1 < len(test_list1)):
         
        # get K segments
        for i in range(K):
            yield test_list1[idx1]
            idx1 += 1
        for i in range(K):
            yield test_list2[idx2]
            idx2 += 1
 
# initializing lists
test_list1 = [4, 3, 8, 2, 6, 7]
test_list2 = [5, 6, 7, 4, 3, 1]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 2
 
# calling helper func. in generator expression
res = [ele for ele in pair_merge(test_list1, test_list2, K)]
 
# printing result
print("The cross joined list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Cross Join every Kth segment
# Using zip_longest() + list comprehension
from itertools import zip_longest, chain
 
# initializing lists
test_list1 = [4, 3, 8, 2, 6, 7]
test_list2 = [5, 6, 7, 4, 3, 1]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 2
 
# zip_longest to get segments
res = [y for idx in zip(zip_longest(*[iter(test_list1)] * K),
      zip_longest(*[iter(test_list2)] * K)) for y in chain.from_iterable(idx) if y]
 
# printing result
print("The cross joined list : " + str(res))


输出
The original list 1 is : [4, 3, 8, 2, 6, 7]
The original list 2 is : [5, 6, 7, 4, 3, 1]
The cross joined list : [4, 3, 5, 6, 8, 2, 7, 4, 6, 7, 3, 1]

方法 #2:使用 zip_longest() + 列表理解

在此,我们使用 zip_longest 获取每个列表的所有元素,列表推导用于两个列表中的迭代任务。

Python3

# Python3 code to demonstrate working of
# Cross Join every Kth segment
# Using zip_longest() + list comprehension
from itertools import zip_longest, chain
 
# initializing lists
test_list1 = [4, 3, 8, 2, 6, 7]
test_list2 = [5, 6, 7, 4, 3, 1]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 2
 
# zip_longest to get segments
res = [y for idx in zip(zip_longest(*[iter(test_list1)] * K),
      zip_longest(*[iter(test_list2)] * K)) for y in chain.from_iterable(idx) if y]
 
# printing result
print("The cross joined list : " + str(res))
输出
The original list 1 is : [4, 3, 8, 2, 6, 7]
The original list 2 is : [5, 6, 7, 4, 3, 1]
The cross joined list : [4, 3, 5, 6, 8, 2, 7, 4, 6, 7, 3, 1]