在Python中由两个具有特定模式的列表组成一个列表

2024-04-19 22:09:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张这样的单子

lst1 = [["a","b"],[1,2,3],[7,8,9,10,11]]
lst2 = [["c","d"],[4,5,6],[12,13,14,15,16]]

我正在尝试实现这样的目标输出:

[["a","b","c","d"],[1,2,4,5],[2,3,5,6],[7,8,12,13],[8,9,13,14],[9,10,14,15],[10,11,15,16]]

编辑:

很抱歉没有包括我到现在为止所做的尝试。你知道吗

test = list(zip(lst1,lst2))
test2 = [item for sublist in test for items in sublist for item in items]

def split(lst, size = 1):
    lsts = []
    while len(lst) > size:
        piece = lst[:size]
        lsts.append(piece)
        lst = lst[size:]
    lsts.append(lst)
    return lsts

print (split(test2, 4))

# prints this 

[['a', 'b', 'c', 'd'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Tags: intestforsizepieceitemsitemsplit
2条回答

在这里,假设列表的格式正确,即所有子列表的长度与另一个数组中的等效子列表的长度相同。你知道吗

lst1 = [["a","b"],[1,2,3],[7,8,9,10,11]]
lst2 = [["c","d"],[4,5,6],[12,13,14,15,16]]

output = []
for s1, s2 in zip(lst1, lst2):
    if len(s1) <= 2:
        output.append(s1 + s2)
    else:
        for index in range(0, len(s1)-1):
            output.append(s1[index:index+2] + s2[index:index+2])

print(output)  

输出:

[['a', 'b', 'c', 'd'], [1, 2, 4, 5], [2, 3, 5, 6], [7, 8, 12, 13], [8, 9, 13, 14], [9, 10, 14, 15], [10, 11, 15, 16]]

您可以使用稍微复杂的列表理解和itertools菜谱中名为^{}的助手函数来实现这一点:

import itertools as it

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = it.tee(iterable)
    next(b, None)
    return zip(a, b)

>>> [x + y for a, b in zip(lst1, lst2) for x, y in zip(pairwise(a), pairwise(b))]
[('a', 'b', 'c', 'd'),
 (1, 2, 4, 5),
 (2, 3, 5, 6),
 (7, 8, 12, 13),
 (8, 9, 13, 14),
 (9, 10, 14, 15),
 (10, 11, 15, 16)]

相关问题 更多 >