Python deep zip

后端 未结 1 533
再見小時候
再見小時候 2021-01-22 06:14

I am trying to write a function like zip. I am not good at explaining what I mean, so i will just show \'code\' of what i\'m trying to do.

a = [1,2,3,[4,5]]
b =          


        
相关标签:
1条回答
  • 2021-01-22 06:44

    I think the following should work:

    import collections
    
    def myzip(*args):
        if all(isinstance(arg, collections.Iterable) for arg in args):
            return [myzip(*vals) for vals in zip(*args)]
        return args
    

    Result:

    >>> a = [1,2,3,[4,[5,6]]]
    >>> b = [1,2,3,[4,[5,6]]]
    >>> myzip(a, b)
    [(1, 1), (2, 2), (3, 3), [(4, 4), [(5, 5), (6, 6)]]]
    

    Note that I use collections.Iterable instead of list in the type checking so that the behavior is more like zip() with tuples and other iterables.

    0 讨论(0)
提交回复
热议问题