左右迭代器添加元素到列表

题目

有两个向量,v1:[1,2,3,4],v2:[5,6,7,8]。通过左右迭代器错位添加元素到列表,得到结果:[1,5,2,6,3,7,4,8]。

代码

def ZigzagIterator(v1,v2):
    ls = []
    while (len(v1) > 0):
        ls.append(v1.pop(0))
        if v2:
            ls.append(v2.pop(0))
    if v2:
        return ls + v2
    return ls

print(ZigzagIterator([1,2,3,4],[5,6,7,8]))

结果

[1, 5, 2, 6, 3, 7, 4, 8]

猜你喜欢

转载自blog.csdn.net/a_13572035650/article/details/128378202