Zip lists in Python

前端 未结 10 2083
无人及你
无人及你 2020-11-22 02:09

I am trying to learn how to \"zip\" lists. To this end, I have a program, where at a particular point, I do the following:

x1, x2, x3 = stuff.calculations(wi         


        
10条回答
  •  无人及你
    2020-11-22 02:26

    In Python 3 zip returns an iterator instead and needs to be passed to a list function to get the zipped tuples:

    x = [1, 2, 3]; y = ['a','b','c']
    z = zip(x, y)
    z = list(z)
    print(z)
    >>> [(1, 'a'), (2, 'b'), (3, 'c')]
    

    Then to unzip them back just conjugate the zipped iterator:

    x_back, y_back = zip(*z)
    print(x_back); print(y_back)
    >>> (1, 2, 3)
    >>> ('a', 'b', 'c')
    

    If the original form of list is needed instead of tuples:

    x_back, y_back = zip(*z)
    print(list(x_back)); print(list(y_back))
    >>> [1,2,3]
    >>> ['a','b','c']
    

提交回复
热议问题