what does zip(*res) mean in python in the following code?

This question already has an answer here:

  • What does the Star operator mean? [duplicate] 5 answers

  • In python, * is the 'splat' operator. It is used for unpacking a list into arguments. For example: foo(*[1, 2, 3]) is the same as foo(1, 2, 3) .

    The zip() function takes n iterables, and returns y tuples, where y is the least of the length of all of the iterables provided. The y th tuple will contain the y th element of all of the iterables provided.

    For example:

    zip(['a', 'b', 'c'], [1, 2, 3])
    

    Will yield

    ('a', 1) ('b', 2) ('c', 3)
    

    For a nested list like res in the example you provided, calling zip(*res) will do something like this:

    res = [['a', 'b', 'c'], [1, 2, 3]]
    zip(*res)
    # this is the same as calling zip(['a', 'b', 'c'], [1, 2, 3])
    ('a', 1)
    ('b', 2)
    ('c', 3)
    

    zip(*res) transposes a matrix (2-d array/list). The * operator 'unpacks' an iterable or rows of a matrix and zip interleaves and zips the rows column-wise:

    > x = [('a', 'b', 'c'), (1, 2, 3)]
    > zip(*x)
    [('a', 1), ('b', 2), ('c', 3)]
    

    Imagine mirroring the matrix on the diagonal.

    链接地址: http://www.djcxy.com/p/53640.html

    上一篇: *解压缩python列表时会做些什么?

    下一篇: 在下面的代码中,zip(* res)在Python中意味着什么?